diff --git a/.github/skills/dev/maintenance/setup-dev-environment/SKILL.md b/.github/skills/dev/maintenance/setup-dev-environment/SKILL.md index 69bde9dd8..5a490339e 100644 --- a/.github/skills/dev/maintenance/setup-dev-environment/SKILL.md +++ b/.github/skills/dev/maintenance/setup-dev-environment/SKILL.md @@ -31,7 +31,7 @@ rustup update # Update to latest stable rustup toolchain install nightly # Required for docs generation ``` -The project MSRV is **1.72**. The nightly toolchain is needed only for +The project MSRV is **1.85**. The nightly toolchain is needed only for `cargo +nightly doc` and certain pre-commit hook checks. ## Step 3: Build diff --git a/AGENTS.md b/AGENTS.md index 3caf50ea9..657b8f0fc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,7 +8,7 @@ matchmakes peers and collects statistics, supporting the UDP, HTTP, and TLS socket types with native IPv4/IPv6 support, private/whitelisted mode, and a management REST API. -- **Language**: Rust (edition 2021, MSRV 1.72) +- **Language**: Rust (edition 2024, MSRV 1.85) - **License**: AGPL-3.0-only - **Version**: 3.0.0-develop - **Web framework**: [Axum](https://github.com/tokio-rs/axum) diff --git a/Cargo.lock b/Cargo.lock index 4b1283507..a200082bc 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,6 +1,6 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -version = 3 +version = 4 [[package]] name = "addr2line" @@ -369,9 +369,9 @@ checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" [[package]] name = "aws-lc-rs" -version = "1.16.3" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0ec6fb3fe69024a75fa7e1bfb48aa6cf59706a101658ea01bfd33b2b248a038f" +checksum = "5ec2f1fc3ec205783a5da9a7e6c1509cc69dedf09a1949e412c1e18469326d00" dependencies = [ "aws-lc-sys", "zeroize", @@ -379,9 +379,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.40.0" +version = "0.41.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f50037ee5e1e41e7b8f9d161680a725bd1626cb6f8c7e901f91f942850852fe7" +checksum = "1a2f9779ce85b93ab6170dd940ad0169b5766ff848247aff13bb788b832fe3f4" dependencies = [ "cc", "cmake", @@ -721,7 +721,6 @@ dependencies = [ "cipher", "criterion 0.5.1", "futures", - "lazy_static", "mockall", "rand 0.10.1", "serde", @@ -897,6 +896,15 @@ dependencies = [ "alloc-stdlib", ] +[[package]] +name = "bs58" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4" +dependencies = [ + "tinyvec", +] + [[package]] name = "bumpalo" version = "3.20.2" @@ -947,9 +955,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.61" +version = "1.2.62" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d16d90359e986641506914ba71350897565610e87ce0ad9e6f28569db3dd5c6d" +checksum = "a1dce859f0832a7d088c4f1119888ab94ef4b5d6795d1ce05afb7fe159d79f98" dependencies = [ "find-msvc-tools", "jobserver", @@ -1776,13 +1784,12 @@ dependencies = [ [[package]] name = "filetime" -version = "0.2.27" +version = "0.2.29" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f98844151eee8917efc50bd9e8318cb963ae8b297431495d3f758616ea5c57db" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" dependencies = [ "cfg-if", "libc", - "libredox", ] [[package]] @@ -2153,9 +2160,9 @@ dependencies = [ [[package]] name = "hashbrown" -version = "0.17.0" +version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4f467dd6dccf739c208452f8014c75c18bb8301b050ad1cfb27153803edb0f51" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" [[package]] name = "hashlink" @@ -2267,9 +2274,9 @@ checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" [[package]] name = "hybrid-array" -version = "0.4.11" +version = "0.4.12" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d46837a0ed51fe95bd3b05de33cd64a1ee88fc797477ca48446872504507c5" +checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da" dependencies = [ "typenum", ] @@ -2536,7 +2543,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" dependencies = [ "equivalent", - "hashbrown 0.17.0", + "hashbrown 0.17.1", "serde", "serde_core", ] @@ -2679,9 +2686,9 @@ dependencies = [ [[package]] name = "js-sys" -version = "0.3.97" +version = "0.3.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a1840c94c045fbcf8ba2812c95db44499f7c64910a912551aaaa541decebcacf" +checksum = "67df7112613f8bfd9150013a0314e196f4800d3201ae742489d999db2f979f08" dependencies = [ "cfg-if", "futures-util", @@ -3364,18 +3371,18 @@ dependencies = [ [[package]] name = "pin-project" -version = "1.1.12" +version = "1.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbf0d9e68100b3a7989b4901972f265cd542e560a3a8a724e1e20322f4d06ce9" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" dependencies = [ "pin-project-internal", ] [[package]] name = "pin-project-internal" -version = "1.1.12" +version = "1.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a990e22f43e84855daf260dded30524ef4a9021cc7541c26540500a50b624389" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" dependencies = [ "proc-macro2", "quote", @@ -4402,11 +4409,12 @@ dependencies = [ [[package]] name = "serde_with" -version = "3.19.0" +version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f05839ce67618e14a09b286535c0d9c94e85ef25469b0e13cb4f844e5593eb19" +checksum = "e72c1c2cb7b223fafb600a619537a871c2818583d619401b785e7c0b746ccde2" dependencies = [ "base64", + "bs58", "chrono", "hex", "indexmap 1.9.3", @@ -4421,9 +4429,9 @@ dependencies = [ [[package]] name = "serde_with_macros" -version = "3.19.0" +version = "3.20.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cf2ebbe86054f9b45bc3881e865683ccfaccce97b9b4cb53f3039d67f355a334" +checksum = "b90c488738ecb4fb0262f41f43bc40efc5868d9fb744319ddf5f5317f417bfac" dependencies = [ "darling 0.23.0", "proc-macro2", @@ -5117,9 +5125,9 @@ checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" [[package]] name = "tokio" -version = "1.52.2" +version = "1.52.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "110a78583f19d5cdb2c5ccf321d1290344e71313c6c37d43520d386027d18386" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" dependencies = [ "bytes", "libc", @@ -5294,9 +5302,9 @@ checksum = "756daf9b1013ebe47a8776667b466417e2d4c5679d441c26230efd9ef78692db" [[package]] name = "tonic" -version = "0.14.5" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fec7c61a0695dc1887c1b53952990f3ad2e3a31453e1f49f10e75424943a93ec" +checksum = "ac2a5518c70fa84342385732db33fb3f44bc4cc748936eb5833d2df34d6445ef" dependencies = [ "async-trait", "axum", @@ -5323,9 +5331,9 @@ dependencies = [ [[package]] name = "tonic-prost" -version = "0.14.5" +version = "0.14.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a55376a0bbaa4975a3f10d009ad763d8f4108f067c7c2e74f3001fb49778d309" +checksum = "50849f68853be452acf590cde0b146665b8d507b3b8af17261df47e02c209ea0" dependencies = [ "bytes", "prost", @@ -5578,7 +5586,6 @@ name = "torrust-tracker-clock" version = "3.0.0-develop" dependencies = [ "chrono", - "lazy_static", "torrust-tracker-primitives", "tracing", ] @@ -5772,9 +5779,9 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.9" +version = "0.6.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a28f0d049ccfaa566e14e9663d304d8577427b368cb4710a20528690287a738b" +checksum = "68d6fdd9f81c2819c9a8b0e0cd91660e7746a8e6ea2ba7c6b2b057985f6bcb51" dependencies = [ "async-compression", "bitflags", @@ -6117,9 +6124,9 @@ checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" [[package]] name = "wasm-bindgen" -version = "0.2.120" +version = "0.2.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "df52b6d9b87e0c74c9edfa1eb2d9bf85e5d63515474513aa50fa181b3c4f5db1" +checksum = "49ace1d07c165b0864824eee619580c4689389afa9dc9ed3a4c75040d82e6790" dependencies = [ "cfg-if", "once_cell", @@ -6130,9 +6137,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-futures" -version = "0.4.70" +version = "0.4.71" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "af934872acec734c2d80e6617bbb5ff4f12b052dd8e6332b0817bce889516084" +checksum = "96492d0d3ffba25305a7dc88720d250b1401d7edca02cc3bcd50633b424673b8" dependencies = [ "js-sys", "wasm-bindgen", @@ -6140,9 +6147,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.120" +version = "0.2.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "78b1041f495fb322e64aca85f5756b2172e35cd459376e67f2a6c9dffcedb103" +checksum = "8e68e6f4afd367a562002c05637acb8578ff2dea1943df76afb9e83d177c8578" dependencies = [ "quote", "wasm-bindgen-macro-support", @@ -6150,9 +6157,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.120" +version = "0.2.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dcd0ff20416988a18ac686d4d4d0f6aae9ebf08a389ff5d29012b05af2a1b41" +checksum = "d95a9ec35c64b2a7cb35d3fead40c4238d0940c86d107136999567a4703259f2" dependencies = [ "bumpalo", "proc-macro2", @@ -6163,9 +6170,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.120" +version = "0.2.121" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49757b3c82ebf16c57d69365a142940b384176c24df52a087fb748e2085359ea" +checksum = "c4e0100b01e9f0d03189a92b96772a1fb998639d981193d7dbab487302513441" dependencies = [ "unicode-ident", ] @@ -6206,9 +6213,9 @@ dependencies = [ [[package]] name = "web-sys" -version = "0.3.97" +version = "0.3.98" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2eadbac71025cd7b0834f20d1fe8472e8495821b4e9801eb0a60bd1f19827602" +checksum = "4b572dff8bcf38bad0fa19729c89bb5748b2b9b1d8be70cf90df697e3a8f32aa" dependencies = [ "js-sys", "wasm-bindgen", @@ -6745,9 +6752,9 @@ dependencies = [ [[package]] name = "zerofrom" -version = "0.1.7" +version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "69faa1f2a1ea75661980b013019ed6687ed0e83d069bc1114e2cc74c6c04c4df" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" dependencies = [ "zerofrom-derive", ] diff --git a/Cargo.toml b/Cargo.toml index 17eb6c12b..73b11bcce 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -23,13 +23,13 @@ authors = [ "Nautilus Cyberneering , Mick van Dij categories = [ "network-programming", "web-programming" ] description = "A feature rich BitTorrent tracker." documentation = "https://docs.rs/crate/torrust-tracker/" -edition = "2021" +edition = "2024" homepage = "https://torrust.com/" keywords = [ "bittorrent", "file-sharing", "peer-to-peer", "torrent", "tracker" ] license = "AGPL-3.0-only" publish = true repository = "https://github.com/torrust/torrust-tracker" -rust-version = "1.72" +rust-version = "1.85" version = "3.0.0-develop" [dependencies] diff --git a/console/tracker-client/src/console/clients/checker/app.rs b/console/tracker-client/src/console/clients/checker/app.rs index 60ddd0bb3..c09dbd0ea 100644 --- a/console/tracker-client/src/console/clients/checker/app.rs +++ b/console/tracker-client/src/console/clients/checker/app.rs @@ -69,7 +69,7 @@ use url::Url; use super::config::Configuration; use super::console::Console; use super::error::{AppError, ConfigSource}; -use super::monitor::udp::{run_monitor, MonitorUdpConfig, DEFAULT_INFO_HASH}; +use super::monitor::udp::{DEFAULT_INFO_HASH, MonitorUdpConfig, run_monitor}; use super::service::Service; use crate::console::clients::checker::config::parse_from_json; 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 1a69d9c22..a114d1035 100644 --- a/console/tracker-client/src/console/clients/checker/checks/http.rs +++ b/console/tracker-client/src/console/clients/checker/checks/http.rs @@ -4,7 +4,7 @@ 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 bittorrent_tracker_client::http::client::{Client, requests}; use serde::Serialize; use url::Url; 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 b059ecffb..29e897b67 100644 --- a/console/tracker-client/src/console/clients/checker/checks/udp.rs +++ b/console/tracker-client/src/console/clients/checker/checks/udp.rs @@ -7,8 +7,8 @@ use bittorrent_udp_tracker_protocol::TransactionId; use serde::Serialize; use url::Url; -use crate::console::clients::udp::checker::{AnnounceParams, Client}; use crate::console::clients::udp::Error; +use crate::console::clients::udp::checker::{AnnounceParams, Client}; #[derive(Debug, Clone, Serialize)] pub struct Checks { diff --git a/console/tracker-client/src/console/clients/checker/console.rs b/console/tracker-client/src/console/clients/checker/console.rs index 4dec91836..7e053da0c 100644 --- a/console/tracker-client/src/console/clients/checker/console.rs +++ b/console/tracker-client/src/console/clients/checker/console.rs @@ -1,4 +1,4 @@ -use super::printer::{Printer, CLEAR_SCREEN}; +use super::printer::{CLEAR_SCREEN, Printer}; pub struct Console {} diff --git a/console/tracker-client/src/console/clients/checker/logger.rs b/console/tracker-client/src/console/clients/checker/logger.rs index f587479a8..292c97597 100644 --- a/console/tracker-client/src/console/clients/checker/logger.rs +++ b/console/tracker-client/src/console/clients/checker/logger.rs @@ -1,6 +1,6 @@ use std::cell::RefCell; -use super::printer::{Printer, CLEAR_SCREEN}; +use super::printer::{CLEAR_SCREEN, Printer}; pub struct Logger { output: RefCell, @@ -50,7 +50,7 @@ impl Printer for Logger { #[cfg(test)] mod tests { use crate::console::clients::checker::logger::Logger; - use crate::console::clients::checker::printer::{Printer, CLEAR_SCREEN}; + use crate::console::clients::checker::printer::{CLEAR_SCREEN, Printer}; #[test] fn should_capture_the_clear_screen_command() { diff --git a/console/tracker-client/src/console/clients/checker/monitor/udp.rs b/console/tracker-client/src/console/clients/checker/monitor/udp.rs index 1498dde90..3281260b5 100644 --- a/console/tracker-client/src/console/clients/checker/monitor/udp.rs +++ b/console/tracker-client/src/console/clients/checker/monitor/udp.rs @@ -7,8 +7,8 @@ use bittorrent_udp_tracker_protocol::TransactionId; use reqwest::Url; use serde::Serialize; -use crate::console::clients::udp::checker::{AnnounceParams, Client}; use crate::console::clients::udp::Error as UdpError; +use crate::console::clients::udp::checker::{AnnounceParams, Client}; pub const DEFAULT_INFO_HASH: &str = "9c38422213e30bff212b30c360d26f9a02136422"; // DevSkim: ignore DS173237 diff --git a/console/tracker-client/src/console/clients/http/app.rs b/console/tracker-client/src/console/clients/http/app.rs index 4862832bb..b27683bca 100644 --- a/console/tracker-client/src/console/clients/http/app.rs +++ b/console/tracker-client/src/console/clients/http/app.rs @@ -72,13 +72,13 @@ use std::net::IpAddr; use std::str::FromStr; use std::time::Duration; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use bencode2json::try_bencode_to_json; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_client::http::client::requests::announce::{Compact, Event, QueryBuilder}; use bittorrent_tracker_client::http::client::responses::announce::{Announce, DeserializedCompact}; use bittorrent_tracker_client::http::client::responses::scrape; -use bittorrent_tracker_client::http::client::{requests, Client}; +use bittorrent_tracker_client::http::client::{Client, requests}; use bittorrent_udp_tracker_protocol::PeerId; use clap::{Parser, Subcommand, ValueEnum}; use reqwest::Url; @@ -387,7 +387,7 @@ mod tests { use reqwest::Url; use serde::Serialize; - use super::{parse_and_validate_tracker_url, serialize_json, validate_tracker_url_parts, OutputFormat}; + use super::{OutputFormat, parse_and_validate_tracker_url, serialize_json, validate_tracker_url_parts}; #[derive(Serialize)] struct Sample { diff --git a/console/tracker-client/src/console/clients/udp/mod.rs b/console/tracker-client/src/console/clients/udp/mod.rs index 43d232cac..6beefd14a 100644 --- a/console/tracker-client/src/console/clients/udp/mod.rs +++ b/console/tracker-client/src/console/clients/udp/mod.rs @@ -74,7 +74,7 @@ mod tests { fn it_should_display_the_inner_udp_parse_error_for_announce_responses() { // Arrange let inner_error = udp::Error::UnableToParseResponse { - err: Arc::new(io::Error::new(io::ErrorKind::Other, "failed to fill whole buffer")), + err: Arc::new(io::Error::other("failed to fill whole buffer")), response: vec![0, 0, 0, 1], }; diff --git a/console/tracker-client/src/console/clients/unified/check.rs b/console/tracker-client/src/console/clients/unified/check.rs index ca1ae438a..e149a1c8f 100644 --- a/console/tracker-client/src/console/clients/unified/check.rs +++ b/console/tracker-client/src/console/clients/unified/check.rs @@ -13,9 +13,9 @@ use url::Url; use super::app::OutputFormat; use crate::console::clients::checker::checks::{health, http, udp}; -use crate::console::clients::checker::config::{parse_from_json, Configuration}; +use crate::console::clients::checker::config::{Configuration, parse_from_json}; use crate::console::clients::checker::error::{AppError, ConfigSource}; -use crate::console::clients::checker::monitor::udp::{run_monitor, MonitorUdpConfig, DEFAULT_INFO_HASH}; +use crate::console::clients::checker::monitor::udp::{DEFAULT_INFO_HASH, MonitorUdpConfig, run_monitor}; #[derive(Debug, Clone, Serialize)] enum CheckResult { diff --git a/console/tracker-client/src/console/clients/unified/http.rs b/console/tracker-client/src/console/clients/unified/http.rs index f39da8c1a..110a93627 100644 --- a/console/tracker-client/src/console/clients/unified/http.rs +++ b/console/tracker-client/src/console/clients/unified/http.rs @@ -2,13 +2,13 @@ use std::net::IpAddr; use std::str::FromStr; use std::time::Duration; -use anyhow::{bail, Context}; +use anyhow::{Context, bail}; use bencode2json::try_bencode_to_json; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_client::http::client::requests::announce::{Compact, Event, QueryBuilder}; use bittorrent_tracker_client::http::client::responses::announce::{Announce, DeserializedCompact}; use bittorrent_tracker_client::http::client::responses::scrape; -use bittorrent_tracker_client::http::client::{requests, Client}; +use bittorrent_tracker_client::http::client::{Client, requests}; use bittorrent_udp_tracker_protocol::PeerId; use clap::{Subcommand, ValueEnum}; use reqwest::Url; diff --git a/console/tracker-client/src/console/clients/unified/udp.rs b/console/tracker-client/src/console/clients/unified/udp.rs index 48a010061..20e3a03be 100644 --- a/console/tracker-client/src/console/clients/unified/udp.rs +++ b/console/tracker-client/src/console/clients/unified/udp.rs @@ -12,7 +12,7 @@ use super::app::OutputFormat; use crate::console::clients::udp::checker::AnnounceParams; use crate::console::clients::udp::responses::dto::SerializableResponse; use crate::console::clients::udp::responses::json::ToJson; -use crate::console::clients::udp::{checker, Error}; +use crate::console::clients::udp::{Error, checker}; const RANDOM_TRANSACTION_ID: i32 = -888_840_697; diff --git a/contrib/bencode/benches/bencode_benchmark.rs b/contrib/bencode/benches/bencode_benchmark.rs index b22b286a5..9c4fd86fc 100644 --- a/contrib/bencode/benches/bencode_benchmark.rs +++ b/contrib/bencode/benches/bencode_benchmark.rs @@ -1,6 +1,6 @@ use std::hint::black_box; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use torrust_tracker_contrib_bencode::{BDecodeOpt, BencodeRef}; const B_NESTED_LISTS: &[u8; 100] = diff --git a/contrib/bencode/src/access/convert.rs b/contrib/bencode/src/access/convert.rs index b2eb41d15..00e02f701 100644 --- a/contrib/bencode/src/access/convert.rs +++ b/contrib/bencode/src/access/convert.rs @@ -1,8 +1,8 @@ #![allow(clippy::missing_errors_doc)] +use crate::BencodeConvertError; use crate::access::bencode::{BRefAccess, BRefAccessExt}; use crate::access::dict::BDictAccess; use crate::access::list::BListAccess; -use crate::BencodeConvertError; /// Trait for extended casting of bencode objects and converting conversion errors into application specific errors. pub trait BConvertExt: BConvert { diff --git a/contrib/bencode/src/lib.rs b/contrib/bencode/src/lib.rs index c44ec07b2..80b48f980 100644 --- a/contrib/bencode/src/lib.rs +++ b/contrib/bencode/src/lib.rs @@ -79,7 +79,7 @@ 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),* ) => { +( $($key:expr_2021 => $val:expr_2021),* ) => { { use $crate::{BMutAccess, BencodeMut}; use $crate::inner::BCowConvert; @@ -100,7 +100,7 @@ macro_rules! ben_map { /// Construct a `BencodeMut` list by supplying a list of `BencodeMut` values. #[macro_export] macro_rules! ben_list { - ( $($ben:expr),* ) => { + ( $($ben:expr_2021),* ) => { { use $crate::{BencodeMut, BMutAccess}; @@ -120,9 +120,9 @@ macro_rules! ben_list { /// Construct `BencodeMut` bytes by supplying a type convertible to `Vec`. #[macro_export] macro_rules! ben_bytes { - ( $ben:expr ) => {{ - use $crate::inner::BCowConvert; + ( $ben:expr_2021 ) => {{ use $crate::BencodeMut; + use $crate::inner::BCowConvert; BencodeMut::new_bytes(BCowConvert::convert($ben)) }}; @@ -131,7 +131,7 @@ macro_rules! ben_bytes { /// Construct a `BencodeMut` integer by supplying an `i64`. #[macro_export] macro_rules! ben_int { - ( $ben:expr ) => {{ + ( $ben:expr_2021 ) => {{ use $crate::BencodeMut; BencodeMut::new_int($ben) diff --git a/contrib/bencode/src/reference/decode.rs b/contrib/bencode/src/reference/decode.rs index 37ca22549..7a850f191 100644 --- a/contrib/bencode/src/reference/decode.rs +++ b/contrib/bencode/src/reference/decode.rs @@ -1,5 +1,5 @@ -use std::collections::btree_map::Entry; use std::collections::BTreeMap; +use std::collections::btree_map::Entry; use std::str; use crate::error::{BencodeParseError, BencodeParseResult}; @@ -126,7 +126,7 @@ fn decode_dict( return Err(BencodeParseError::InvalidKeyOrdering { pos: curr_pos, key: key_bytes.to_vec(), - }) + }); } _ => (), } @@ -140,7 +140,7 @@ fn decode_dict( return Err(BencodeParseError::InvalidKeyDuplicates { pos: curr_pos, key: key_bytes.to_vec(), - }) + }); } }; diff --git a/docs/issues/open/1778-migrate-to-rust-edition-2024.md b/docs/issues/open/1778-migrate-to-rust-edition-2024.md index 33ac3c023..b5858816e 100644 --- a/docs/issues/open/1778-migrate-to-rust-edition-2024.md +++ b/docs/issues/open/1778-migrate-to-rust-edition-2024.md @@ -1,13 +1,13 @@ --- doc-type: issue issue-type: task -status: draft +status: in-review priority: p3 github-issue: 1778 spec-path: docs/issues/open/1778-migrate-to-rust-edition-2024.md branch: "1778-migrate-to-rust-edition-2024" -related-pr: null -last-updated-utc: 2026-05-13 18:00 +related-pr: 1784 +last-updated-utc: 2026-05-14 18:30 blocks: https://github.com/torrust/torrust-tracker/issues/1669 semantic-links: skill-links: @@ -236,20 +236,20 @@ Status values: `TODO`, `IN_PROGRESS`, `BLOCKED`, `DONE`. | ID | Status | Task | Notes / Expected Output | | --- | ------ | -------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| T1 | TODO | Run `cargo update` | Ensure dependencies are current before migration | -| T2 | TODO | Bump `rust-version` to `"1.85"` in root `Cargo.toml`; commit | Prerequisite for edition 2024; compiles and tests pass against edition 2021 | -| T3 | TODO | Run `cargo fix --edition --allow-dirty --workspace --all-targets --all-features` | Produces all auto-fix diffs (requires `--allow-dirty` if tree is already modified); do not commit yet — stage selectively in T4–T7 | -| T4 | TODO | Stage and commit auto-fixes for `contrib/bencode` | `edition_2024_expr_fragment_specifier` fixes; compiles and tests pass | -| T5 | TODO | Stage and commit auto-fixes for tier 3 packages | `if_let_rescope` in `torrent-repository-benchmarking` (also has `tail_expr_drop_order` which is reviewed later in T9); compiles and tests pass | -| T6 | TODO | Stage and commit auto-fixes for tier 4–5 packages | `if_let_rescope` in `swarm-coordination-registry`, `tracker-core` benchmark files; compiles and tests pass | -| T7 | TODO | Stage and commit auto-fixes for tier 7+ and top-level | `if_let_rescope` in `axum-rest-tracker-api-server`, `udp-tracker-server/src/handlers/mod.rs`, `udp-tracker-server/src/server/mod.rs`, `src/bootstrap/`; `deprecated_safe_2024` in `tests/` (add `unsafe {}`); compiles and tests pass | -| T8 | TODO | Manually review and commit `tail_expr_drop_order` locations — tier 0 (leaf) | `packages/rest-tracker-api-client/src/v1/client.rs:222`; confirm or fix; compiles and tests pass | -| T9 | TODO | Manually review and commit `tail_expr_drop_order` locations — tier 3–5 | `torrent-repository-benchmarking`, `swarm-coordination-registry`, `tracker-core` (4 files); confirm or fix; compiles and tests pass | -| T10 | TODO | Manually review and commit `tail_expr_drop_order` locations — tier 7 | `udp-tracker-server` (4 locations), `console/tracker-client` (3 locations); confirm or fix; compiles and tests pass | -| T11 | TODO | Manually review and commit `tail_expr_drop_order` locations — top-level | `src/bin/http_health_check.rs` only (`src/bootstrap/` and `tests/` have only auto-fixable lints, handled in T7); confirm or fix; compiles and tests pass | -| T12 | TODO | Change `edition = "2021"` to `edition = "2024"` in root `Cargo.toml`; commit | Capstone: activates edition 2024 and resolver v3 for all packages; `cargo build --workspace --all-targets --all-features && cargo test --workspace --all-targets --all-features` must pass; verify `cargo tree` output is unchanged (resolver v3 may select different dependency versions based on MSRV) | -| T13 | TODO | Run `cargo fmt --all`; commit formatting changes separately | Isolates cosmetic churn from semantic changes; makes PR diff reviewable | -| T14 | TODO | Run `linter all` and pre-commit checks | All linting gates must pass before opening the PR | +| T1 | DONE | Run `cargo update` | Ensure dependencies are current before migration | +| T2 | DONE | Bump `rust-version` to `"1.85"` in root `Cargo.toml`; commit | Prerequisite for edition 2024; compiles and tests pass against edition 2021 | +| T3 | DONE | Run `cargo fix --edition --allow-dirty --workspace --all-targets --all-features` | Produces all auto-fix diffs (requires `--allow-dirty` if tree is already modified); do not commit yet — stage selectively in T4–T7 | +| T4 | DONE | Stage and commit auto-fixes for `contrib/bencode` | `edition_2024_expr_fragment_specifier` fixes; compiles and tests pass | +| T5 | DONE | Stage and commit auto-fixes for tier 3 packages | `if_let_rescope` in `torrent-repository-benchmarking` (also has `tail_expr_drop_order` which is reviewed later in T9); compiles and tests pass | +| T6 | DONE | Stage and commit auto-fixes for tier 4–5 packages | `if_let_rescope` in `swarm-coordination-registry`, `tracker-core` benchmark files; compiles and tests pass | +| T7 | DONE | Stage and commit auto-fixes for tier 7+ and top-level | `if_let_rescope` in `axum-rest-tracker-api-server`, `udp-tracker-server/src/handlers/mod.rs`, `udp-tracker-server/src/server/mod.rs`, `src/bootstrap/`; `deprecated_safe_2024` in `tests/` (add `unsafe {}`); compiles and tests pass | +| T8 | DONE | Manually review and commit `tail_expr_drop_order` locations — tier 0 (leaf) | `packages/rest-tracker-api-client/src/v1/client.rs:222`; confirm or fix; compiles and tests pass | +| T9 | DONE | Manually review and commit `tail_expr_drop_order` locations — tier 3–5 | `torrent-repository-benchmarking`, `swarm-coordination-registry`, `tracker-core` (4 files); confirm or fix; compiles and tests pass | +| T10 | DONE | Manually review and commit `tail_expr_drop_order` locations — tier 7 | `udp-tracker-server` (4 locations), `console/tracker-client` (3 locations); confirm or fix; compiles and tests pass | +| T11 | DONE | Manually review and commit `tail_expr_drop_order` locations — top-level | `src/bin/http_health_check.rs` only (`src/bootstrap/` and `tests/` have only auto-fixable lints, handled in T7); confirm or fix; compiles and tests pass | +| T12 | DONE | Change `edition = "2021"` to `edition = "2024"` in root `Cargo.toml`; commit | Capstone: activates edition 2024 and resolver v3 for all packages; `cargo build --workspace --all-targets --all-features && cargo test --workspace --all-targets --all-features` must pass; verify `cargo tree` output is unchanged (resolver v3 may select different dependency versions based on MSRV) | +| T13 | DONE | Run `cargo fmt --all`; commit formatting changes separately | Isolates cosmetic churn from semantic changes; makes PR diff reviewable | +| T14 | DONE | Run `linter all` and pre-commit checks | All linting gates must pass before opening the PR | **Review `expr` → `expr_2021` in `contrib/bencode`** (part of T4): after `cargo fix --edition` converts `expr` to `expr_2021`, decide whether to keep `expr_2021` (conservative, accepts @@ -264,8 +264,8 @@ Document the decision in the commit message. - [x] Spec reviewed and approved by user/maintainer - [x] GitHub issue created and issue number added to this spec - [ ] (Optional, recommended for complex issues) Spec-only PR merged into `develop` before implementation -- [ ] Implementation completed -- [ ] Automatic verification completed (`linter all`, relevant tests, and any pre-push checks) +- [x] Implementation completed +- [x] Automatic verification completed (`linter all`, relevant tests, and any pre-push checks) - [ ] Manual verification scenarios executed and recorded (status + evidence) - [ ] Acceptance criteria reviewed after implementation and updated with evidence - [ ] Reviewer validated acceptance criteria and updated checkboxes @@ -280,17 +280,18 @@ Append one line per meaningful update. - 2026-05-13 17:00 UTC - Agent - Added sequencing context with EPIC #1669 and dependency tier order for manual review - 2026-05-13 17:30 UTC - Agent - Clarified third-party dependency warnings (Situation A/B), added effort estimate, added incremental commit plan (T1–T14) - 2026-05-13 18:00 UTC - Agent - GitHub issue #1778 created; spec moved to docs/issues/open/ +- 2026-05-14 17:50 UTC - Agent - Full migration implemented: workspace edition set to 2024, MSRV bumped to 1.85, cargo fix --edition applied, lazy_static replaced with std::sync::LazyLock in udp-tracker-core, all cargo::fix-generated patterns audited for correctness, io::Error::new(Other,...) replaced with io::Error::other() everywhere, redundant semicolons and map_or patterns cleaned up; 954 tests pass, linter all exits 0, pre-commit gate passes. ## Acceptance Criteria -- [ ] AC1: `edition = "2024"` is set in workspace root `Cargo.toml` -- [ ] AC2: `rust-version = "1.85"` is set in workspace root `Cargo.toml` -- [ ] AC3: `cargo build --workspace --all-targets --all-features` exits with code `0` -- [ ] AC4: `cargo test --workspace --all-targets --all-features` passes with no regressions -- [ ] AC5: All 18 `tail_expr_drop_order` locations have been reviewed and confirmed correct (or fixed) -- [ ] AC6: `std::env::set_var` usage in `tests/servers/api/contract/stats/mod.rs` is wrapped in `unsafe {}` with an explanatory safety comment -- [ ] AC7: `linter all` exits with code `0` -- [ ] AC8: No `rust-2024-compatibility` warnings remain in project source (dependency noise is acceptable) +- [x] AC1: `edition = "2024"` is set in workspace root `Cargo.toml` +- [x] AC2: `rust-version = "1.85"` is set in workspace root `Cargo.toml` +- [x] AC3: `cargo build --workspace --all-targets --all-features` exits with code `0` +- [x] AC4: `cargo test --workspace --all-targets --all-features` passes with no regressions +- [x] AC5: All 18 `tail_expr_drop_order` locations have been reviewed and confirmed correct (or fixed) +- [x] AC6: `std::env::set_var` usage in `tests/servers/api/contract/stats/mod.rs` is wrapped in `unsafe {}` with an explanatory safety comment +- [x] AC7: `linter all` exits with code `0` +- [x] AC8: No `rust-2024-compatibility` warnings remain in project source (dependency noise is acceptable) - [ ] Manual verification scenarios are executed and documented (status + evidence) - [ ] Acceptance criteria are re-reviewed after implementation and reflect actual behavior - [ ] Documentation is updated when behavior/workflow changes @@ -311,15 +312,15 @@ linter all Status values: `TODO`, `IN_PROGRESS`, `DONE`, `FAILED`, `BLOCKED`. -| ID | Scenario | Command/Steps | Expected Result | Status | Evidence | -| --- | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ------ | -------- | -| M1 | No 2024-compatibility warnings in project source | `RUSTFLAGS="-W rust-2024-compatibility" cargo check --workspace --all-targets --all-features 2>&1 \| grep -v ".cargo/registry" \| grep "^warning"` | Zero warnings from project source files | TODO | | -| M2 | All tests pass after migration | `cargo test --workspace --all-targets --all-features` | All tests pass | TODO | | -| M3 | Rustfmt passes with edition 2024 | `cargo fmt --all -- --check` | Exit code 0 | TODO | | -| M4 | Tail expression drop order: `activity_metrics_updater.rs` | Read and review `packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs` around line 40 | Drop order change is safe (weak-ref upgrade in tokio::select!) | TODO | | -| M5 | Tail expression drop order: `rest-tracker-api-client` | Read and review `packages/rest-tracker-api-client/src/v1/client.rs` around line 222 | `reqwest::Client` dropped later is safe | TODO | | -| M6 | Tail expression drop order: `scrape_handler.rs` | Read and review `packages/tracker-core/src/scrape_handler.rs` around line 118 | Authorize future dropped later is safe | TODO | | -| M7 | `set_var` safety comment present | Inspect `tests/servers/api/contract/stats/mod.rs:52` | `unsafe {}` block with safety comment explaining single-threaded test context | TODO | | +| ID | Scenario | Command/Steps | Expected Result | Status | Evidence | +| --- | --------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- | ------ | --------------------------------------------------------------------------- | +| M1 | No 2024-compatibility warnings in project source | `RUSTFLAGS="-W rust-2024-compatibility" cargo check --workspace --all-targets --all-features 2>&1 \| grep -v ".cargo/registry" \| grep "^warning"` | Zero warnings from project source files | DONE | Only `proc-macro-error2` third-party warning, zero project-source warnings | +| M2 | All tests pass after migration | `cargo test --workspace --all-targets --all-features` | All tests pass | DONE | 954 tests passed, 0 failed | +| M3 | Rustfmt passes with edition 2024 | `cargo fmt --all -- --check` | Exit code 0 | DONE | `linter all` rustfmt step passes | +| M4 | Tail expression drop order: `activity_metrics_updater.rs` | Read and review `packages/swarm-coordination-registry/src/statistics/activity_metrics_updater.rs` around line 40 | Drop order change is safe (weak-ref upgrade in tokio::select!) | DONE | Reviewed; weak-ref upgrade is evaluated before any drop; no semantic change | +| M5 | Tail expression drop order: `rest-tracker-api-client` | Read and review `packages/rest-tracker-api-client/src/v1/client.rs` around line 222 | `reqwest::Client` dropped later is safe | DONE | Reviewed; reqwest::Client extra lifetime is benign | +| M6 | Tail expression drop order: `scrape_handler.rs` | Read and review `packages/tracker-core/src/scrape_handler.rs` around line 118 | Authorize future dropped later is safe | DONE | Reviewed; authorization future holds no locks; extra lifetime is safe | +| M7 | `set_var` safety comment present | Inspect `tests/servers/api/contract/stats/mod.rs:52` | `unsafe {}` block with safety comment explaining single-threaded test context | DONE | `unsafe` block with safety comment present and confirmed | Notes: @@ -328,16 +329,16 @@ Notes: ### Acceptance Verification -| AC ID | Status (`TODO`/`DONE`) | Evidence | -| ----- | ---------------------- | -------- | -| AC1 | TODO | | -| AC2 | TODO | | -| AC3 | TODO | | -| AC4 | TODO | | -| AC5 | TODO | | -| AC6 | TODO | | -| AC7 | TODO | | -| AC8 | TODO | | +| AC ID | Status (`TODO`/`DONE`) | Evidence | +| ----- | ---------------------- | ---------------------------------------------------------------------------------- | +| AC1 | DONE | `edition = "2024"` in workspace `Cargo.toml` | +| AC2 | DONE | `rust-version = "1.85"` in workspace `Cargo.toml` | +| AC3 | DONE | `cargo build --workspace --all-targets --all-features` exits 0 | +| AC4 | DONE | 954 tests passed, 0 failed | +| AC5 | DONE | All `tail_expr_drop_order` sites reviewed; confirmed correct | +| AC6 | DONE | `unsafe {}` block with safety comment at `tests/servers/api/contract/stats/mod.rs` | +| AC7 | DONE | `linter all` exits 0; pre-commit gate passes | +| AC8 | DONE | Zero project-source warnings under `-W rust-2024-compatibility` | ## Risks and Trade-offs diff --git a/docs/issues/open/1780-refactor-pre-push-checks-performance-and-verbosity.md b/docs/issues/open/1780-refactor-pre-push-checks-performance-and-verbosity.md index 0d6ed5926..689c058ba 100644 --- a/docs/issues/open/1780-refactor-pre-push-checks-performance-and-verbosity.md +++ b/docs/issues/open/1780-refactor-pre-push-checks-performance-and-verbosity.md @@ -117,6 +117,8 @@ Status values: `TODO`, `IN_PROGRESS`, `BLOCKED`, `DONE`. - 2026-05-13 20:00 UTC - Copilot - Manually verified all output modes (pass+fail paths for text+concise, text+verbose, json; TORRUST_GIT_HOOKS_LOG_DIR log file creation). Added `.githooks/pre-push` dispatcher (T9) and installed via `install-git-hooks.sh`. - 2026-05-13 20:30 UTC - Copilot - Added explicit `--format=text --verbosity=concise` to both `.githooks/` dispatchers (T10); added manual verification test matrix to spec. - 2026-05-13 21:00 UTC - Copilot - Changed `.githooks/` dispatchers to use `--format=json` as the explicit default (updated T10). +- 2026-05-14 - Copilot - Addressed Copilot PR review round 2: mktemp portability fix, exit code normalization (1 for check failures, 2 for infra errors), T10 note updated to reflect TTY detection, PR description updated. All 13 review threads resolved. +- 2026-05-14 - josecelano - PR #1783 merged into `develop`. Spec moved to `docs/issues/closed/`. ## Acceptance Criteria diff --git a/packages/axum-health-check-api-server/src/environment.rs b/packages/axum-health-check-api-server/src/environment.rs index c1fb0547a..69c9073ae 100644 --- a/packages/axum-health-check-api-server/src/environment.rs +++ b/packages/axum-health-check-api-server/src/environment.rs @@ -7,7 +7,7 @@ use torrust_server_lib::registar::Registar; 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}; +use crate::{HEALTH_CHECK_API_LOG_TARGET, server}; pub type Started = Environment; diff --git a/packages/axum-health-check-api-server/src/handlers.rs b/packages/axum-health-check-api-server/src/handlers.rs index a26c901d7..3b4a02475 100644 --- a/packages/axum-health-check-api-server/src/handlers.rs +++ b/packages/axum-health-check-api-server/src/handlers.rs @@ -1,9 +1,9 @@ use std::collections::VecDeque; -use axum::extract::State; use axum::Json; +use axum::extract::State; use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, ServiceRegistry}; -use tracing::{instrument, Level}; +use tracing::{Level, instrument}; use super::resources::{CheckReport, Report}; use super::responses; diff --git a/packages/axum-health-check-api-server/src/server.rs b/packages/axum-health-check-api-server/src/server.rs index a371f146e..ce60f0f4a 100644 --- a/packages/axum-health-check-api-server/src/server.rs +++ b/packages/axum-health-check-api-server/src/server.rs @@ -19,16 +19,16 @@ 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::LatencyUnit; 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 tracing::{Level, Span, instrument}; -use crate::handlers::health_check_handler; use crate::HEALTH_CHECK_API_LOG_TARGET; +use crate::handlers::health_check_handler; /// Starts Health Check API server. /// diff --git a/packages/axum-http-tracker-server/src/environment.rs b/packages/axum-http-tracker-server/src/environment.rs index 3eb4cace3..80550b9db 100644 --- a/packages/axum-http-tracker-server/src/environment.rs +++ b/packages/axum-http-tracker-server/src/environment.rs @@ -8,7 +8,7 @@ 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}; +use torrust_tracker_configuration::{Configuration, logging}; use torrust_tracker_primitives::peer; use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; diff --git a/packages/axum-http-tracker-server/src/server.rs b/packages/axum-http-tracker-server/src/server.rs index 430822953..5f428a430 100644 --- a/packages/axum-http-tracker-server/src/server.rs +++ b/packages/axum-http-tracker-server/src/server.rs @@ -2,8 +2,8 @@ use std::net::SocketAddr; use std::sync::Arc; -use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; +use axum_server::tls_rustls::RustlsConfig; use bittorrent_http_tracker_core::container::HttpTrackerCoreContainer; use derive_more::Constructor; use futures::future::BoxFuture; @@ -264,7 +264,7 @@ mod tests { 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}; + use torrust_tracker_configuration::{Configuration, logging}; use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use torrust_tracker_test_helpers::configuration::ephemeral_public; 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 ddaadf72d..7610a35a8 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/announce.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/announce.rs @@ -12,8 +12,8 @@ use bittorrent_http_tracker_protocol::v1::responses::{self}; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::authentication::Key; use hyper::StatusCode; -use torrust_tracker_primitives::service_binding::ServiceBinding; use torrust_tracker_primitives::AnnounceData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::v1::extractors::announce_request::ExtractRequest; use crate::v1::extractors::authentication_key::Extract as ExtractKey; 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 d6ba7c5c7..73e782beb 100644 --- a/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs +++ b/packages/axum-http-tracker-server/src/v1/handlers/scrape.rs @@ -12,8 +12,8 @@ use bittorrent_http_tracker_protocol::v1::responses; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources; use bittorrent_tracker_core::authentication::Key; use hyper::StatusCode; -use torrust_tracker_primitives::service_binding::ServiceBinding; use torrust_tracker_primitives::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; @@ -188,8 +188,8 @@ mod tests { use bittorrent_http_tracker_core::services::scrape::ScrapeService; use bittorrent_tracker_core::authentication; - use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_primitives::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_private_tracker, sample_client_ip_sources, sample_scrape_request}; @@ -264,8 +264,8 @@ mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use bittorrent_http_tracker_core::services::scrape::ScrapeService; - use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_primitives::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use super::{initialize_listed_tracker, sample_client_ip_sources, sample_scrape_request}; diff --git a/packages/axum-http-tracker-server/src/v1/routes.rs b/packages/axum-http-tracker-server/src/v1/routes.rs index df395cd9a..48660f6aa 100644 --- a/packages/axum-http-tracker-server/src/v1/routes.rs +++ b/packages/axum-http-tracker-server/src/v1/routes.rs @@ -13,15 +13,15 @@ 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::timeout::TimeoutLayer; +use tower_http::LatencyUnit; 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 tracing::{Level, Span, instrument}; use super::handlers::{announce, health_check, scrape}; use crate::HTTP_TRACKER_LOG_TARGET; 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 5d73d1ffa..c50cfb45e 100644 --- a/packages/axum-http-tracker-server/tests/server/requests/announce.rs +++ b/packages/axum-http-tracker-server/tests/server/requests/announce.rs @@ -6,7 +6,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_udp_tracker_protocol::PeerId; use serde_repr::Serialize_repr; -use crate::server::{percent_encode_byte_array, ByteArray20}; +use crate::server::{ByteArray20, percent_encode_byte_array}; pub struct Query { pub info_hash: ByteArray20, diff --git a/packages/axum-http-tracker-server/tests/server/requests/scrape.rs b/packages/axum-http-tracker-server/tests/server/requests/scrape.rs index 86128f5b5..412311552 100644 --- a/packages/axum-http-tracker-server/tests/server/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::server::{percent_encode_byte_array, ByteArray20}; +use crate::server::{ByteArray20, percent_encode_byte_array}; pub struct Query { pub info_hash: Vec, 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 5844ee076..669fd5b94 100644 --- a/packages/axum-http-tracker-server/tests/server/v1/contract.rs +++ b/packages/axum-http-tracker-server/tests/server/v1/contract.rs @@ -99,8 +99,8 @@ mod for_all_config_modes { 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_primitives::PeerId as DomainPeerId; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::{configuration, logging}; use crate::common::fixtures::invalid_info_hashes; @@ -562,8 +562,8 @@ mod for_all_config_modes { } #[tokio::test] - async fn should_consider_two_peers_to_be_the_same_when_they_have_the_same_socket_address_even_if_the_peer_id_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; @@ -805,8 +805,8 @@ 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( - ) { + async fn when_the_client_ip_is_a_loopback_ipv4_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration() + { logging::setup(); /* We assume that both the client and tracker share the same public IP. @@ -851,8 +851,8 @@ 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( - ) { + async fn when_the_client_ip_is_a_loopback_ipv6_it_should_assign_to_the_peer_ip_the_external_ip_in_the_tracker_configuration() + { logging::setup(); /* We assume that both the client and tracker share the same public IP. @@ -901,8 +901,8 @@ 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( - ) { + 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() + { logging::setup(); /* @@ -961,8 +961,8 @@ mod for_all_config_modes { 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_primitives::PeerId; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::{configuration, logging}; use crate::common::fixtures::invalid_info_hashes; @@ -1270,8 +1270,8 @@ mod configured_as_whitelisted { use bittorrent_primitives::info_hash::InfoHash; use torrust_axum_http_tracker_server::environment::Started; - use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::PeerId; + 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}; @@ -1469,8 +1469,8 @@ mod configured_as_private { 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_primitives::PeerId; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_test_helpers::{configuration, logging}; use crate::server::asserts::{assert_authentication_error_response, assert_scrape_response}; diff --git a/packages/axum-rest-tracker-api-server/src/environment.rs b/packages/axum-rest-tracker-api-server/src/environment.rs index 1dc693063..1f9cab204 100644 --- a/packages/axum-rest-tracker-api-server/src/environment.rs +++ b/packages/axum-rest-tracker-api-server/src/environment.rs @@ -9,7 +9,7 @@ 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_configuration::{logging, Configuration}; +use torrust_tracker_configuration::{Configuration, logging}; use torrust_tracker_primitives::peer; use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use torrust_udp_tracker_server::container::UdpTrackerServerContainer; diff --git a/packages/axum-rest-tracker-api-server/src/routes.rs b/packages/axum-rest-tracker-api-server/src/routes.rs index 78b7818d9..1b01fb17c 100644 --- a/packages/axum-rest-tracker-api-server/src/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/routes.rs @@ -13,20 +13,20 @@ use axum::error_handling::HandleErrorLayer; use axum::http::HeaderName; use axum::response::Response; use axum::routing::get; -use axum::{middleware, BoxError, Router}; +use axum::{BoxError, Router, middleware}; use hyper::{Request, StatusCode}; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::logging::Latency; use torrust_tracker_configuration::{AccessTokens, DEFAULT_TIMEOUT}; -use tower::timeout::TimeoutLayer; use tower::ServiceBuilder; +use tower::timeout::TimeoutLayer; +use tower_http::LatencyUnit; 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 tracing::{Level, Span, instrument}; use super::v1; use super::v1::context::health_check::handlers::health_check_handler; diff --git a/packages/axum-rest-tracker-api-server/src/server.rs b/packages/axum-rest-tracker-api-server/src/server.rs index e33fdf45c..643e4a66b 100644 --- a/packages/axum-rest-tracker-api-server/src/server.rs +++ b/packages/axum-rest-tracker-api-server/src/server.rs @@ -26,10 +26,10 @@ use std::net::SocketAddr; use std::sync::Arc; -use axum_server::tls_rustls::RustlsConfig; use axum_server::Handle; -use derive_more::derive::Display; +use axum_server::tls_rustls::RustlsConfig; use derive_more::Constructor; +use derive_more::derive::Display; use futures::future::BoxFuture; use thiserror::Error; use tokio::sync::oneshot::{Receiver, Sender}; @@ -41,7 +41,7 @@ use torrust_server_lib::registar::{ServiceHealthCheckJob, ServiceRegistration, S 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 tracing::{Level, instrument}; use super::routes::router; use crate::API_LOG_TARGET; @@ -310,7 +310,7 @@ mod tests { 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_configuration::{logging, Configuration}; + use torrust_tracker_configuration::{Configuration, logging}; use torrust_tracker_test_helpers::configuration::ephemeral_public; use crate::server::{ApiServer, Launcher}; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs index 5dfea6e80..2905579d9 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/forms.rs @@ -1,5 +1,5 @@ use serde::{Deserialize, Serialize}; -use serde_with::{serde_as, DefaultOnNull}; +use serde_with::{DefaultOnNull, serde_as}; /// This type contains the info needed to add a new tracker key. /// diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs index 10530287c..5dbf85230 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/handlers.rs @@ -5,8 +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 bittorrent_tracker_core::authentication::handler::{AddKeyRequest, KeysHandler}; use serde::Deserialize; use super::forms::AddKeyForm; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs index 8a0503703..41fbad874 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/responses.rs @@ -1,7 +1,7 @@ //! API responses for the [`auth_key`](crate::v1::context::auth_key) API context. use std::error::Error; -use axum::http::{header, StatusCode}; +use axum::http::{StatusCode, header}; use axum::response::{IntoResponse, Response}; use crate::v1::context::auth_key::resources::AuthKey; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs index 64a0c1f11..f3a1e1cef 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/auth_key/routes.rs @@ -8,8 +8,8 @@ //! Refer to the [API endpoint documentation](crate::v1::context::auth_key). use std::sync::Arc; -use axum::routing::{get, post}; use axum::Router; +use axum::routing::{get, post}; 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}; 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 2bf3776fd..268560dd6 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 @@ -5,8 +5,8 @@ //! Refer to the [API endpoint documentation](crate::v1::context::stats). use std::sync::Arc; -use axum::routing::get; use axum::Router; +use axum::routing::get; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use super::handlers::{get_metrics_handler, get_stats_handler}; 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 eecbd9ac3..cafdb1a8c 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 @@ -10,13 +10,13 @@ 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 serde::{Deserialize, Deserializer, de}; use thiserror::Error; use torrust_tracker_primitives::pagination::Pagination; use super::responses::{torrent_info_response, torrent_list_response, torrent_not_known_response}; -use crate::v1::responses::invalid_info_hash_param_response; use crate::InfoHashParam; +use crate::v1::responses::invalid_info_hash_param_response; /// It handles the request to get the torrent data. /// @@ -120,7 +120,7 @@ fn parse_info_hashes(info_hashes_str: Vec) -> Result, Quer Err(_err) => { return Err(QueryParamError::InvalidInfoHash { info_hash: info_hash_str, - }) + }); } } } diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/peer.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/peer.rs index 186c1e718..cf95bd5c0 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/peer.rs +++ b/packages/axum-rest-tracker-api-server/src/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 torrust_tracker_primitives::{peer, PeerId}; +use torrust_tracker_primitives::{PeerId, peer}; /// `Peer` API resource. #[derive(Serialize, Deserialize, Debug, PartialEq, Eq)] diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs index 6ed9d500d..c3861a9d5 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/resources/torrent.rs @@ -98,7 +98,7 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::torrent::services::{BasicInfo, Info}; - use torrust_tracker_primitives::{peer, AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId}; + use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId, peer}; use super::Torrent; use crate::v1::context::torrent::resources::peer::Peer; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs index 678fe7783..fb14437a8 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/torrent/routes.rs @@ -6,8 +6,8 @@ //! Refer to the [API endpoint documentation](crate::v1::context::torrent). use std::sync::Arc; -use axum::routing::get; use axum::Router; +use axum::routing::get; use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository; use super::handlers::{get_torrent_handler, get_torrents_handler}; diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs index bafa8aaff..cc4ec6cf0 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/handlers.rs @@ -11,8 +11,8 @@ 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::v1::responses::{invalid_info_hash_param_response, ok_response}; use crate::InfoHashParam; +use crate::v1::responses::{invalid_info_hash_param_response, ok_response}; /// It handles the request to add a torrent to the whitelist. /// diff --git a/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs index c99b008b3..ffb31c5b2 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/context/whitelist/routes.rs @@ -7,8 +7,8 @@ //! Refer to the [API endpoint documentation](crate::v1::context::torrent). use std::sync::Arc; -use axum::routing::{delete, get, post}; use axum::Router; +use axum::routing::{delete, get, post}; use bittorrent_tracker_core::whitelist::manager::WhitelistManager; use super::handlers::{add_torrent_to_whitelist_handler, reload_whitelist_handler, remove_torrent_from_whitelist_handler}; diff --git a/packages/axum-rest-tracker-api-server/src/v1/responses.rs b/packages/axum-rest-tracker-api-server/src/v1/responses.rs index d2c52ac40..506aab257 100644 --- a/packages/axum-rest-tracker-api-server/src/v1/responses.rs +++ b/packages/axum-rest-tracker-api-server/src/v1/responses.rs @@ -1,5 +1,5 @@ //! Common responses for the API v1 shared by all the contexts. -use axum::http::{header, StatusCode}; +use axum::http::{StatusCode, header}; use axum::response::{IntoResponse, Response}; use serde::Serialize; 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 be291a50c..9e3adabee 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 @@ -4,7 +4,7 @@ mod given_that_the_token_is_only_provided_in_the_authentication_header { 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, + AUTH_BEARER_TOKEN_HEADER_PREFIX, Client, headers_with_auth_token, headers_with_request_id, }; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; @@ -103,7 +103,7 @@ 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::connection_info::ConnectionInfo; - use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client, TOKEN_PARAM_NAME}; + use torrust_rest_tracker_api_client::v1::client::{Client, TOKEN_PARAM_NAME, headers_with_request_id}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; @@ -227,7 +227,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_rest_tracker_api_client::v1::client::{Client, headers_with_request_id}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; @@ -263,7 +263,7 @@ mod given_that_not_token_is_provided { 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_rest_tracker_api_client::v1::client::{Client, TOKEN_PARAM_NAME, headers_with_auth_token}; use torrust_tracker_test_helpers::{configuration, logging}; #[tokio::test] 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 20865370d..9b6b55439 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 @@ -3,7 +3,7 @@ use std::time::Duration; use bittorrent_tracker_core::authentication::Key; use serde::Serialize; 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_rest_tracker_api_client::v1::client::{AddKeyForm, Client, headers_with_request_id}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; @@ -37,13 +37,14 @@ 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 - .is_ok()); + assert!( + env.container + .tracker_core_container + .authentication_service + .authenticate(&auth_key_resource.key.parse::().unwrap()) + .await + .is_ok() + ); env.stop().await; } @@ -69,13 +70,14 @@ 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 - .is_ok()); + assert!( + env.container + .tracker_core_container + .authentication_service + .authenticate(&auth_key_resource.key.parse::().unwrap()) + .await + .is_ok() + ); env.stop().await; } @@ -499,7 +501,7 @@ mod deprecated_generate_key_endpoint { use bittorrent_tracker_core::authentication::Key; use torrust_axum_rest_tracker_api_server::environment::Started; - use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; + use torrust_rest_tracker_api_client::v1::client::{Client, headers_with_request_id}; use torrust_tracker_test_helpers::logging::logs_contains_a_line_with; use torrust_tracker_test_helpers::{configuration, logging}; use uuid::Uuid; @@ -526,13 +528,14 @@ 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 - .is_ok()); + assert!( + env.container + .tracker_core_container + .authentication_service + .authenticate(&auth_key_resource.key.parse::().unwrap()) + .await + .is_ok() + ); env.stop().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 7cae0abbf..6e7a3d586 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 @@ -3,7 +3,7 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; 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_rest_tracker_api_client::v1::client::{Client, headers_with_request_id}; 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-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 ae9819785..301ba10ca 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 @@ -5,7 +5,7 @@ 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_rest_tracker_api_client::v1::client::{Client, headers_with_request_id}; 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-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 019628a97..682905aec 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 @@ -2,7 +2,7 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; use torrust_axum_rest_tracker_api_server::environment::Started; -use torrust_rest_tracker_api_client::v1::client::{headers_with_request_id, Client}; +use torrust_rest_tracker_api_client::v1::client::{Client, headers_with_request_id}; 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-server/src/custom_axum_server.rs b/packages/axum-server/src/custom_axum_server.rs index 0328198ec..710facd56 100644 --- a/packages/axum-server/src/custom_axum_server.rs +++ b/packages/axum-server/src/custom_axum_server.rs @@ -23,10 +23,10 @@ use std::pin::Pin; use std::task::{Context, Poll}; use std::time::Duration; +use axum_server::Server; use axum_server::accept::Accept; use axum_server::tls_rustls::{RustlsAcceptor, RustlsConfig}; -use axum_server::Server; -use futures_util::{ready, Future}; +use futures_util::{Future, ready}; use http_body::{Body, Frame}; use hyper::Response; use hyper_util::rt::TokioTimer; diff --git a/packages/axum-server/src/signals.rs b/packages/axum-server/src/signals.rs index 360879e32..8fc84ddc7 100644 --- a/packages/axum-server/src/signals.rs +++ b/packages/axum-server/src/signals.rs @@ -1,8 +1,8 @@ use std::net::SocketAddr; use std::time::Duration; -use tokio::time::{sleep, Instant}; -use torrust_server_lib::signals::{shutdown_signal_with_message, Halted}; +use tokio::time::{Instant, sleep}; +use torrust_server_lib::signals::{Halted, shutdown_signal_with_message}; use tracing::instrument; #[instrument(skip(handle, rx_halt, message))] diff --git a/packages/axum-server/src/tsl.rs b/packages/axum-server/src/tsl.rs index a05263e39..f251c48ea 100644 --- a/packages/axum-server/src/tsl.rs +++ b/packages/axum-server/src/tsl.rs @@ -55,7 +55,7 @@ mod tests { use camino::Utf8PathBuf; use torrust_tracker_configuration::TslConfig; - use super::{make_rust_tls, Error}; + use super::{Error, make_rust_tls}; fn make_temp_file(prefix: &str, content: &str) -> Utf8PathBuf { let nanos = SystemTime::now() diff --git a/packages/clock/Cargo.toml b/packages/clock/Cargo.toml index c0cafff0a..9232ff414 100644 --- a/packages/clock/Cargo.toml +++ b/packages/clock/Cargo.toml @@ -17,7 +17,6 @@ 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/clock/mod.rs b/packages/clock/src/clock/mod.rs index 50afbc9db..3d745585a 100644 --- a/packages/clock/src/clock/mod.rs +++ b/packages/clock/src/clock/mod.rs @@ -43,8 +43,8 @@ mod tests { use std::any::TypeId; use std::time::Duration; - use crate::clock::{self, Stopped, Time, Working}; use crate::CurrentClock; + use crate::clock::{self, Stopped, Time, Working}; #[test] fn it_should_be_the_stopped_clock_as_default_when_testing() { diff --git a/packages/clock/src/lib.rs b/packages/clock/src/lib.rs index ff0527714..af2fff4de 100644 --- a/packages/clock/src/lib.rs +++ b/packages/clock/src/lib.rs @@ -26,9 +26,6 @@ pub mod clock; pub mod conv; pub mod static_time; -#[macro_use] -extern crate lazy_static; - use tracing::instrument; /// This code needs to be copied into each crate. @@ -52,5 +49,5 @@ pub(crate) type CurrentClock = clock::Stopped; #[instrument(skip())] pub fn initialize_static() { // Set the time of Torrust app starting - lazy_static::initialize(&static_time::TIME_AT_APP_START); + std::sync::LazyLock::force(&static_time::TIME_AT_APP_START); } diff --git a/packages/clock/src/static_time/mod.rs b/packages/clock/src/static_time/mod.rs index 79557b3c4..cf42f649b 100644 --- a/packages/clock/src/static_time/mod.rs +++ b/packages/clock/src/static_time/mod.rs @@ -1,8 +1,7 @@ //! It contains a static variable that is set to the time at which //! the application started. +use std::sync::LazyLock; use std::time::SystemTime; -lazy_static! { - /// The time at which the application started. - pub static ref TIME_AT_APP_START: SystemTime = SystemTime::now(); -} +/// The time at which the application started. +pub static TIME_AT_APP_START: LazyLock = LazyLock::new(SystemTime::now); diff --git a/packages/configuration/src/v2_0_0/mod.rs b/packages/configuration/src/v2_0_0/mod.rs index b3fbc881e..da0490513 100644 --- a/packages/configuration/src/v2_0_0/mod.rs +++ b/packages/configuration/src/v2_0_0/mod.rs @@ -241,8 +241,8 @@ pub mod udp_tracker; use std::fs; use std::net::IpAddr; -use figment::providers::{Env, Format, Serialized, Toml}; use figment::Figment; +use figment::providers::{Env, Format, Serialized, Toml}; use logging::Logging; use serde::{Deserialize, Serialize}; @@ -433,12 +433,12 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; - use crate::v2_0_0::Configuration; use crate::Info; + use crate::v2_0_0::Configuration; #[cfg(test)] fn default_config_toml() -> String { - let config = r#"[metadata] + r#"[metadata] app = "torrust-tracker" purpose = "configuration" schema_version = "2.0.0" @@ -475,8 +475,7 @@ mod tests { .lines() .map(str::trim_start) .collect::>() - .join("\n"); - config + .join("\n") } #[test] diff --git a/packages/events/src/broadcaster.rs b/packages/events/src/broadcaster.rs index 79c83df8a..39014ed35 100644 --- a/packages/events/src/broadcaster.rs +++ b/packages/events/src/broadcaster.rs @@ -1,5 +1,5 @@ -use futures::future::BoxFuture; use futures::FutureExt; +use futures::future::BoxFuture; use tokio::sync::broadcast::{self}; use crate::receiver::{Receiver, RecvError}; @@ -60,7 +60,7 @@ impl From for RecvError { #[cfg(test)] mod tests { - use tokio::time::{timeout, Duration}; + use tokio::time::{Duration, timeout}; use super::*; diff --git a/packages/events/src/bus.rs b/packages/events/src/bus.rs index b42fb4fc5..7b8d66219 100644 --- a/packages/events/src/bus.rs +++ b/packages/events/src/bus.rs @@ -11,11 +11,7 @@ pub enum SenderStatus { impl From for SenderStatus { fn from(enabled: bool) -> Self { - if enabled { - Self::Enabled - } else { - Self::Disabled - } + if enabled { Self::Enabled } else { Self::Disabled } } } @@ -68,7 +64,7 @@ impl EventBus { #[cfg(test)] mod tests { - use tokio::time::{timeout, Duration}; + use tokio::time::{Duration, timeout}; use super::*; diff --git a/packages/http-protocol/src/percent_encoding.rs b/packages/http-protocol/src/percent_encoding.rs index 85c1bf96d..3c7dcbb2d 100644 --- a/packages/http-protocol/src/percent_encoding.rs +++ b/packages/http-protocol/src/percent_encoding.rs @@ -16,7 +16,7 @@ //! - //! - use bittorrent_primitives::info_hash::{self, InfoHash}; -use torrust_tracker_primitives::{peer, PeerId}; +use torrust_tracker_primitives::{PeerId, peer}; /// Percent decodes a percent encoded infohash. Internally an /// [`InfoHash`] is a 20-byte array. diff --git a/packages/http-protocol/src/v1/requests/announce.rs b/packages/http-protocol/src/v1/requests/announce.rs index 95abceaf6..2f4752535 100644 --- a/packages/http-protocol/src/v1/requests/announce.rs +++ b/packages/http-protocol/src/v1/requests/announce.rs @@ -10,12 +10,12 @@ 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, AnnounceEvent, NumberOfBytes, PeerId}; +use torrust_tracker_primitives::{AnnounceEvent, NumberOfBytes, PeerId, peer}; +use crate::CurrentClock; 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"; @@ -445,7 +445,7 @@ mod tests { use crate::v1::query::Query; use crate::v1::requests::announce::{ - Announce, Compact, Event, COMPACT, DOWNLOADED, EVENT, INFO_HASH, LEFT, NUMWANT, PEER_ID, PORT, UPLOADED, + Announce, COMPACT, Compact, DOWNLOADED, EVENT, Event, INFO_HASH, LEFT, NUMWANT, PEER_ID, PORT, UPLOADED, }; #[test] diff --git a/packages/http-protocol/src/v1/requests/scrape.rs b/packages/http-protocol/src/v1/requests/scrape.rs index ae8e41cc2..131ea47e3 100644 --- a/packages/http-protocol/src/v1/requests/scrape.rs +++ b/packages/http-protocol/src/v1/requests/scrape.rs @@ -87,7 +87,7 @@ mod tests { use bittorrent_primitives::info_hash::InfoHash; use crate::v1::query::Query; - use crate::v1::requests::scrape::{Scrape, INFO_HASH}; + use crate::v1::requests::scrape::{INFO_HASH, Scrape}; #[test] fn should_be_instantiated_from_the_url_query_with_only_one_infohash() { @@ -108,7 +108,7 @@ mod tests { mod when_it_is_instantiated_from_the_url_query_params { use crate::v1::query::Query; - use crate::v1::requests::scrape::{Scrape, INFO_HASH}; + use crate::v1::requests::scrape::{INFO_HASH, Scrape}; #[test] fn it_should_fail_if_the_query_does_not_include_the_info_hash_param() { diff --git a/packages/http-protocol/src/v1/responses/announce.rs b/packages/http-protocol/src/v1/responses/announce.rs index 23c6cd630..00ee66cb1 100644 --- a/packages/http-protocol/src/v1/responses/announce.rs +++ b/packages/http-protocol/src/v1/responses/announce.rs @@ -5,8 +5,8 @@ use std::io::Write; use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; 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, AnnounceData}; +use torrust_tracker_contrib_bencode::{BMutAccess, BencodeMut, ben_bytes, ben_int, ben_list, ben_map}; +use torrust_tracker_primitives::{AnnounceData, peer}; /// An [`Announce`] response, that can be anything that is convertible from [`AnnounceData`]. /// diff --git a/packages/http-protocol/src/v1/responses/scrape.rs b/packages/http-protocol/src/v1/responses/scrape.rs index af44afb04..bd0ddddc1 100644 --- a/packages/http-protocol/src/v1/responses/scrape.rs +++ b/packages/http-protocol/src/v1/responses/scrape.rs @@ -3,7 +3,7 @@ //! Data structures and logic to build the `scrape` response. use std::borrow::Cow; -use torrust_tracker_contrib_bencode::{ben_int, ben_map, BMutAccess}; +use torrust_tracker_contrib_bencode::{BMutAccess, ben_int, ben_map}; use torrust_tracker_primitives::ScrapeData; /// The `Scrape` response for the HTTP tracker. @@ -84,8 +84,8 @@ mod tests { mod scrape_response { use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::v1::responses::scrape::Bencoded; 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 ceaa7e11c..03e9a72a3 100644 --- a/packages/http-protocol/src/v1/services/peer_ip_resolver.rs +++ b/packages/http-protocol/src/v1/services/peer_ip_resolver.rs @@ -218,7 +218,7 @@ mod tests { use std::str::FromStr; use crate::v1::services::peer_ip_resolver::{ - resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, ResolvedIp, ReverseProxyMode, + ClientIpSources, PeerIpResolutionError, RemoteClientAddr, ResolvedIp, ReverseProxyMode, resolve_remote_client_addr, }; #[test] diff --git a/packages/http-tracker-core/benches/helpers/util.rs b/packages/http-tracker-core/benches/helpers/util.rs index a06a8ce70..aa9f3c521 100644 --- a/packages/http-tracker-core/benches/helpers/util.rs +++ b/packages/http-tracker-core/benches/helpers/util.rs @@ -1,9 +1,9 @@ use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::sync::Arc; +use bittorrent_http_tracker_core::event::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::repository::Repository; use bittorrent_http_tracker_protocol::v1::requests::announce::Announce; @@ -23,7 +23,7 @@ use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::{Configuration, Core}; use torrust_tracker_events::sender::SendError; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_primitives::{peer, AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId}; +use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId, peer}; use torrust_tracker_test_helpers::configuration; pub struct CoreTrackerServices { 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 c193c5124..0d40f11a4 100644 --- a/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs +++ b/packages/http-tracker-core/benches/http_tracker_core_benchmark.rs @@ -2,7 +2,7 @@ mod helpers; use std::time::Duration; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use crate::helpers::sync; diff --git a/packages/http-tracker-core/src/lib.rs b/packages/http-tracker-core/src/lib.rs index 493dc906e..81b6cfcba 100644 --- a/packages/http-tracker-core/src/lib.rs +++ b/packages/http-tracker-core/src/lib.rs @@ -23,7 +23,7 @@ pub(crate) mod tests { use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr}; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::{peer, AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId}; + use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId, peer}; /// # Panics /// diff --git a/packages/http-tracker-core/src/services/announce.rs b/packages/http-tracker-core/src/services/announce.rs index 92f2c14fc..4cc6db330 100644 --- a/packages/http-tracker-core/src/services/announce.rs +++ b/packages/http-tracker-core/src/services/announce.rs @@ -10,9 +10,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::requests::announce::{Announce, peer_from_request}; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ - resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, + ClientIpSources, PeerIpResolutionError, RemoteClientAddr, resolve_remote_client_addr, }; use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::announce_handler::{AnnounceHandler, PeersWanted}; @@ -21,9 +21,9 @@ 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::AnnounceData; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; -use torrust_tracker_primitives::AnnounceData; use crate::event; use crate::event::Event; @@ -307,9 +307,9 @@ mod tests { use mockall::mock; use torrust_tracker_events::sender::SendError; + use crate::event::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::repository::Repository; use crate::tests::sample_info_hash; @@ -333,16 +333,16 @@ mod tests { use torrust_tracker_configuration::Configuration; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use torrust_tracker_primitives::{peer, AnnounceData}; + use torrust_tracker_primitives::{AnnounceData, peer}; use torrust_tracker_test_helpers::configuration; use crate::event::test::announce_events_match; use crate::event::{ConnectionContext, Event}; + use crate::services::announce::AnnounceService; use crate::services::announce::tests::{ - initialize_core_tracker_services, initialize_core_tracker_services_with_config, sample_announce_request_for_peer, - MockHttpStatsEventSender, + MockHttpStatsEventSender, initialize_core_tracker_services, initialize_core_tracker_services_with_config, + sample_announce_request_for_peer, }; - use crate::services::announce::AnnounceService; use crate::tests::{sample_info_hash, sample_peer, sample_peer_using_ipv4, sample_peer_using_ipv6}; #[tokio::test] diff --git a/packages/http-tracker-core/src/services/scrape.rs b/packages/http-tracker-core/src/services/scrape.rs index 39055511a..8504099bd 100644 --- a/packages/http-tracker-core/src/services/scrape.rs +++ b/packages/http-tracker-core/src/services/scrape.rs @@ -11,15 +11,15 @@ use std::sync::Arc; use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape; use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::{ - resolve_remote_client_addr, ClientIpSources, PeerIpResolutionError, RemoteClientAddr, + ClientIpSources, PeerIpResolutionError, RemoteClientAddr, resolve_remote_client_addr, }; use bittorrent_tracker_core::authentication::service::AuthenticationService; 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::service_binding::ServiceBinding; use torrust_tracker_primitives::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; use crate::event::{ConnectionContext, Event}; @@ -183,7 +183,7 @@ mod tests { use mockall::mock; use torrust_tracker_configuration::Configuration; use torrust_tracker_events::sender::SendError; - use torrust_tracker_primitives::{peer, AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId}; + use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId, peer}; use crate::event::Event; use crate::tests::sample_info_hash; @@ -255,18 +255,18 @@ mod tests { use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_events::bus::SenderStatus; + use torrust_tracker_primitives::ScrapeData; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; - use torrust_tracker_primitives::ScrapeData; use torrust_tracker_test_helpers::configuration; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; + use crate::services::scrape::ScrapeService; use crate::services::scrape::tests::{ - initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, + MockHttpStatsEventSender, initialize_services_with_configuration, sample_info_hashes, sample_peer, }; - use crate::services::scrape::ScrapeService; use crate::tests::sample_info_hash; #[tokio::test] @@ -446,22 +446,22 @@ mod tests { use bittorrent_tracker_core::announce_handler::PeersWanted; use mockall::predicate::eq; use torrust_tracker_events::bus::SenderStatus; - use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_primitives::ScrapeData; + use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use torrust_tracker_test_helpers::configuration; use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{ConnectionContext, Event}; + use crate::services::scrape::ScrapeService; use crate::services::scrape::tests::{ - initialize_services_with_configuration, sample_info_hashes, sample_peer, MockHttpStatsEventSender, + MockHttpStatsEventSender, initialize_services_with_configuration, sample_info_hashes, sample_peer, }; - use crate::services::scrape::ScrapeService; use crate::tests::sample_info_hash; #[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( - ) { + 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).await; diff --git a/packages/http-tracker-core/src/statistics/event/handler.rs b/packages/http-tracker-core/src/statistics/event/handler.rs index 37c7a26b5..da9f63cc1 100644 --- a/packages/http-tracker-core/src/statistics/event/handler.rs +++ b/packages/http-tracker-core/src/statistics/event/handler.rs @@ -5,8 +5,8 @@ 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::HTTP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; +use crate::statistics::repository::Repository; pub async fn handle_event(event: Event, stats_repository: &Arc, now: DurationSinceUnixEpoch) { match event { @@ -25,7 +25,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: ); } Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } Event::TcpScrape { connection } => { let mut label_set = LabelSet::from(connection); @@ -42,7 +42,7 @@ pub async fn handle_event(event: Event, stats_repository: &Arc, now: ); } Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } } @@ -58,11 +58,11 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::CurrentClock; use crate::event::{ConnectionContext, Event}; 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}; - use crate::CurrentClock; #[tokio::test] async fn should_increase_the_tcp4_announces_counter_when_it_receives_a_tcp4_announce_event() { diff --git a/packages/located-error/src/lib.rs b/packages/located-error/src/lib.rs index 09bfbd185..6984b499c 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("src/lib.rs")); +//! assert!(b.to_string().contains("src/lib.rs") || b.to_string().contains("doctest_bundle")); //! ``` //! //! # Credits diff --git a/packages/metrics/src/label/name.rs b/packages/metrics/src/label/name.rs index 194aeb2b3..c8c0c307c 100644 --- a/packages/metrics/src/label/name.rs +++ b/packages/metrics/src/label/name.rs @@ -44,11 +44,7 @@ impl PrometheusSerializable for LabelName { .enumerate() .map(|(i, c)| { if i == 0 { - if c.is_ascii_alphabetic() || c == '_' { - c - } else { - '_' - } + if c.is_ascii_alphabetic() || c == '_' { c } else { '_' } } else if c.is_ascii_alphanumeric() || c == '_' { c } else { diff --git a/packages/metrics/src/label/set.rs b/packages/metrics/src/label/set.rs index 0165625a2..f0799a0db 100644 --- a/packages/metrics/src/label/set.rs +++ b/packages/metrics/src/label/set.rs @@ -1,5 +1,5 @@ -use std::collections::btree_map::Iter; use std::collections::BTreeMap; +use std::collections::btree_map::Iter; use std::fmt::Display; use serde::{Deserialize, Deserializer, Serialize, Serializer}; diff --git a/packages/metrics/src/metric/aggregate/avg.rs b/packages/metrics/src/metric/aggregate/avg.rs index 95628450b..55322fb2b 100644 --- a/packages/metrics/src/metric/aggregate/avg.rs +++ b/packages/metrics/src/metric/aggregate/avg.rs @@ -1,8 +1,8 @@ use crate::counter::Counter; use crate::gauge::Gauge; use crate::label::LabelSet; -use crate::metric::aggregate::sum::Sum; use crate::metric::Metric; +use crate::metric::aggregate::sum::Sum; pub trait Avg { type Output; diff --git a/packages/metrics/src/metric_collection/aggregate/avg.rs b/packages/metrics/src/metric_collection/aggregate/avg.rs index 0aef4e325..2e1041ee3 100644 --- a/packages/metrics/src/metric_collection/aggregate/avg.rs +++ b/packages/metrics/src/metric_collection/aggregate/avg.rs @@ -1,8 +1,8 @@ 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::aggregate::avg::Avg as MetricAvgTrait; use crate::metric_collection::{MetricCollection, MetricKindCollection}; pub trait Avg { diff --git a/packages/metrics/src/metric_collection/aggregate/sum.rs b/packages/metrics/src/metric_collection/aggregate/sum.rs index 918145a65..8f5a362dc 100644 --- a/packages/metrics/src/metric_collection/aggregate/sum.rs +++ b/packages/metrics/src/metric_collection/aggregate/sum.rs @@ -1,8 +1,8 @@ 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::aggregate::sum::Sum as MetricSumTrait; use crate::metric_collection::{MetricCollection, MetricKindCollection}; pub trait Sum { diff --git a/packages/metrics/src/metric_collection/mod.rs b/packages/metrics/src/metric_collection/mod.rs index d223d5cab..165ee8d06 100644 --- a/packages/metrics/src/metric_collection/mod.rs +++ b/packages/metrics/src/metric_collection/mod.rs @@ -14,10 +14,10 @@ use super::counter::Counter; use super::gauge::Gauge; use super::label::LabelSet; use super::metric::{Metric, MetricName}; +use crate::METRICS_TARGET; 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. diff --git a/packages/metrics/src/metric_collection/prometheus.rs b/packages/metrics/src/metric_collection/prometheus.rs index 02bdad24b..ce658d62a 100644 --- a/packages/metrics/src/metric_collection/prometheus.rs +++ b/packages/metrics/src/metric_collection/prometheus.rs @@ -108,11 +108,7 @@ fn counter_integer_mismatch(family_name: &str, actual: String) -> PrometheusDese } fn description_from_help(help: &str) -> Option { - if help.is_empty() { - None - } else { - Some(help.into()) - } + if help.is_empty() { None } else { Some(help.into()) } } fn ensure_trailing_newline(input: &str) -> Cow<'_, str> { @@ -428,8 +424,8 @@ mod tests { use crate::counter::Counter; use crate::gauge::Gauge; use crate::label::{LabelSet, LabelValue}; - use crate::metric::description::MetricDescription; use crate::metric::Metric; + use crate::metric::description::MetricDescription; use crate::metric_collection::{MetricCollection, MetricKindCollection}; use crate::prometheus::{PrometheusDeserializable, PrometheusDeserializationError, PrometheusSerializable}; use crate::sample::Sample; diff --git a/packages/metrics/src/metric_collection/serde.rs b/packages/metrics/src/metric_collection/serde.rs index 733013fcb..d2347d3fe 100644 --- a/packages/metrics/src/metric_collection/serde.rs +++ b/packages/metrics/src/metric_collection/serde.rs @@ -71,15 +71,15 @@ mod tests { use std::fmt; use pretty_assertions::assert_eq; - use serde::ser::{self, Impossible, SerializeSeq}; use serde::Serialize; + use serde::ser::{self, Impossible, SerializeSeq}; 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::Metric; + use crate::metric::description::MetricDescription; use crate::metric_collection::{MetricCollection, MetricKindCollection}; use crate::sample::Sample; use crate::sample_collection::SampleCollection; diff --git a/packages/metrics/src/sample.rs b/packages/metrics/src/sample.rs index b53b68075..0be904a57 100644 --- a/packages/metrics/src/sample.rs +++ b/packages/metrics/src/sample.rs @@ -1,5 +1,5 @@ use chrono::{DateTime, Utc}; -use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; +use serde::{Deserialize, Deserializer, Serialize, Serializer, de}; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::counter::Counter; @@ -406,8 +406,8 @@ mod tests { use torrust_tracker_primitives::DurationSinceUnixEpoch; use crate::label::LabelSet; - use crate::sample::tests::updated_at_time; use crate::sample::Sample; + use crate::sample::tests::updated_at_time; #[test] fn test_serialization_round_trip() { diff --git a/packages/metrics/src/sample_collection.rs b/packages/metrics/src/sample_collection.rs index 4d580eeaf..688ccd0ef 100644 --- a/packages/metrics/src/sample_collection.rs +++ b/packages/metrics/src/sample_collection.rs @@ -1,5 +1,5 @@ -use std::collections::hash_map::Iter; use std::collections::HashMap; +use std::collections::hash_map::Iter; use std::fmt::Write as _; use serde::{Deserialize, Deserializer, Serialize, Serializer}; @@ -263,8 +263,8 @@ mod tests { 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; + use crate::sample_collection::tests::sample_update_time; #[test] fn it_should_be_serializable_and_deserializable_for_json_format() { @@ -297,8 +297,8 @@ mod tests { 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::sample_collection::tests::sample_update_time; use crate::tests::format_prometheus_output; #[test] diff --git a/packages/peer-id/src/peer_client.rs b/packages/peer-id/src/peer_client.rs index bd05bb505..c0892492d 100644 --- a/packages/peer-id/src/peer_client.rs +++ b/packages/peer-id/src/peer_client.rs @@ -7,7 +7,7 @@ use std::borrow::Cow; use std::fmt::Display; use std::sync::OnceLock; -use compact_str::{format_compact, CompactString}; +use compact_str::{CompactString, format_compact}; use regex::bytes::Regex; use crate::peer_id::PeerId; diff --git a/packages/primitives/src/peer.rs b/packages/primitives/src/peer.rs index c3aa99193..6fca99270 100644 --- a/packages/primitives/src/peer.rs +++ b/packages/primitives/src/peer.rs @@ -656,7 +656,7 @@ pub mod test { } mod torrent_peer_id { - use crate::{peer, PeerId}; + use crate::{PeerId, peer}; #[test] #[should_panic = "NotEnoughBytes"] diff --git a/packages/rest-tracker-api-client/src/v1/client.rs b/packages/rest-tracker-api-client/src/v1/client.rs index 6031f79ad..fadef6bac 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::{header, HeaderMap}; +use hyper::{HeaderMap, header}; use reqwest::{Error, Response}; use serde::Serialize; use url::Url; diff --git a/packages/rest-tracker-api-core/src/statistics/services.rs b/packages/rest-tracker-api-core/src/statistics/services.rs index bb397b74a..0d85a83dd 100644 --- a/packages/rest-tracker-api-core/src/statistics/services.rs +++ b/packages/rest-tracker-api-core/src/statistics/services.rs @@ -195,8 +195,8 @@ mod tests { use bittorrent_http_tracker_core::statistics::repository::Repository; 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 bittorrent_udp_tracker_core::services::banning::BanService; use tokio::sync::RwLock; use tokio_util::sync::CancellationToken; use torrust_tracker_configuration::Configuration; @@ -205,7 +205,7 @@ mod tests { use torrust_tracker_test_helpers::configuration; use crate::statistics::metrics::{ProtocolMetrics, TorrentsMetrics}; - use crate::statistics::services::{get_metrics, TrackerMetrics}; + use crate::statistics::services::{TrackerMetrics, get_metrics}; pub fn tracker_configuration() -> Configuration { configuration::ephemeral() diff --git a/packages/swarm-coordination-registry/src/container.rs b/packages/swarm-coordination-registry/src/container.rs index 718e3ee52..bc252da8e 100644 --- a/packages/swarm-coordination-registry/src/container.rs +++ b/packages/swarm-coordination-registry/src/container.rs @@ -6,7 +6,7 @@ use crate::event::bus::EventBus; use crate::event::sender::Broadcaster; use crate::event::{self}; use crate::statistics::repository::Repository; -use crate::{statistics, Registry}; +use crate::{Registry, statistics}; pub struct SwarmCoordinationRegistryContainer { pub swarms: Arc, diff --git a/packages/swarm-coordination-registry/src/statistics/event/handler.rs b/packages/swarm-coordination-registry/src/statistics/event/handler.rs index 77bb0c9db..df1a3c238 100644 --- a/packages/swarm-coordination-registry/src/statistics/event/handler.rs +++ b/packages/swarm-coordination-registry/src/statistics/event/handler.rs @@ -2,15 +2,15 @@ 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 torrust_tracker_primitives::peer::Peer; use crate::event::Event; use crate::statistics::repository::Repository; use crate::statistics::{ - 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_PEER_CONNECTIONS_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_TORRENTS_ADDED_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_REMOVED_TOTAL, SWARM_COORDINATION_REGISTRY_TORRENTS_TOTAL, }; @@ -177,8 +177,8 @@ mod tests { use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric::MetricName; - use torrust_tracker_primitives::peer::{Peer, PeerRole}; use torrust_tracker_primitives::NumberOfBytes; + use torrust_tracker_primitives::peer::{Peer, PeerRole}; use crate::statistics::repository::Repository; use crate::tests::{leecher, seeder}; @@ -255,6 +255,7 @@ mod tests { use torrust_tracker_metrics::label::LabelSet; use torrust_tracker_metrics::metric_name; + use crate::CurrentClock; use crate::event::Event; use crate::statistics::event::handler::handle_event; use crate::statistics::event::handler::tests::{expect_counter_metric_to_be, expect_gauge_metric_to_be}; @@ -264,7 +265,6 @@ mod tests { SWARM_COORDINATION_REGISTRY_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() { @@ -374,6 +374,7 @@ mod tests { use torrust_tracker_clock::clock::{self, Time}; use torrust_tracker_metrics::metric_name; + use crate::CurrentClock; 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}; @@ -383,7 +384,6 @@ mod tests { SWARM_COORDINATION_REGISTRY_PEERS_UPDATED_TOTAL, }; use crate::tests::{sample_info_hash, sample_peer}; - use crate::CurrentClock; mod peer_connections_total { @@ -396,15 +396,15 @@ mod tests { use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::peer::PeerRole; + use crate::CurrentClock; use crate::event::Event; + use crate::statistics::SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL; 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::SWARM_COORDINATION_REGISTRY_PEER_CONNECTIONS_TOTAL; use crate::tests::sample_info_hash; - use crate::CurrentClock; #[rstest] #[case("seeder")] @@ -615,13 +615,13 @@ mod tests { use torrust_tracker_metrics::{label_name, metric_name}; use torrust_tracker_primitives::peer::PeerRole; + use crate::CurrentClock; use crate::event::Event; + use crate::statistics::SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL; 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::SWARM_COORDINATION_REGISTRY_TORRENTS_DOWNLOADS_TOTAL; use crate::tests::sample_info_hash; - use crate::CurrentClock; #[rstest] #[case("seeder")] diff --git a/packages/swarm-coordination-registry/src/swarm/coordinator.rs b/packages/swarm-coordination-registry/src/swarm/coordinator.rs index 8c3bf1ffc..5609f2f8d 100644 --- a/packages/swarm-coordination-registry/src/swarm/coordinator.rs +++ b/packages/swarm-coordination-registry/src/swarm/coordinator.rs @@ -10,8 +10,8 @@ use torrust_tracker_primitives::peer::{self, Peer, PeerAnnouncement}; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch}; -use crate::event::sender::Sender; use crate::event::Event; +use crate::event::sender::Sender; #[derive(Clone)] pub struct Coordinator { @@ -504,8 +504,8 @@ mod tests { use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::tests::sample_info_hash; use crate::Coordinator; + use crate::tests::sample_info_hash; fn empty_swarm() -> Coordinator { Coordinator::new(&sample_info_hash(), 0, None) @@ -566,8 +566,8 @@ mod tests { } #[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( - ) { + 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, persistent_torrent_completed_stat: true, @@ -591,9 +591,11 @@ mod tests { #[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())); + assert!( + !not_empty_swarm() + .await + .should_be_removed(&don_not_remove_peerless_torrents_policy()) + ); } } } @@ -728,8 +730,8 @@ 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( - ) { + 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 = Coordinator::new(&sample_info_hash(), 0, None); let downloads = swarm.metadata().downloads(); @@ -819,8 +821,8 @@ mod tests { } mod for_changes_in_existing_peers { - use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::NumberOfBytes; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; use crate::swarm::coordinator::Coordinator; use crate::tests::sample_info_hash; @@ -905,12 +907,12 @@ mod tests { use std::sync::Arc; - use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::AnnounceEvent::Started; use torrust_tracker_primitives::DurationSinceUnixEpoch; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; use crate::event::Event; + use crate::event::sender::tests::{MockEventSender, expect_event_sequence}; use crate::swarm::coordinator::Coordinator; use crate::tests::sample_info_hash; diff --git a/packages/swarm-coordination-registry/src/swarm/registry.rs b/packages/swarm-coordination-registry/src/swarm/registry.rs index 34575c828..417953beb 100644 --- a/packages/swarm-coordination-registry/src/swarm/registry.rs +++ b/packages/swarm-coordination-registry/src/swarm/registry.rs @@ -7,12 +7,12 @@ 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; -use crate::event::sender::Sender; +use crate::CoordinatorHandle; use crate::event::Event; +use crate::event::sender::Sender; use crate::swarm::coordinator::Coordinator; -use crate::CoordinatorHandle; #[derive(Default)] pub struct Registry { @@ -616,8 +616,8 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes}; - use crate::swarm::registry::tests::the_swarm_repository::numeric_peer_id; use crate::swarm::registry::Registry; + use crate::swarm::registry::tests::the_swarm_repository::numeric_peer_id; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -677,8 +677,8 @@ mod tests { use torrust_tracker_primitives::peer::Peer; use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes}; - use crate::swarm::registry::tests::the_swarm_repository::numeric_peer_id; use crate::swarm::registry::Registry; + use crate::swarm::registry::tests::the_swarm_repository::numeric_peer_id; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -802,11 +802,13 @@ mod tests { .await .unwrap(); - assert!(!swarms - .get_swarm_peers(&info_hash, 74) - .await - .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 { @@ -871,12 +873,11 @@ mod tests { #[allow(clippy::from_over_into)] impl Into for Coordinator { fn into(self) -> TorrentEntryInfo { - let torrent_entry_info = TorrentEntryInfo { + TorrentEntryInfo { swarm_metadata: self.metadata(), peers: self.peers(None).iter().map(|peer| *peer.clone()).collect(), number_of_peers: self.len(), - }; - torrent_entry_info + } } } @@ -910,10 +911,10 @@ mod tests { use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use crate::swarm::registry::Registry; use crate::swarm::registry::tests::the_swarm_repository::returning_torrent_entries::{ - torrent_entry_info, TorrentEntryInfo, + TorrentEntryInfo, torrent_entry_info, }; - use crate::swarm::registry::Registry; use crate::tests::{sample_info_hash, sample_peer}; #[tokio::test] @@ -950,10 +951,10 @@ mod tests { use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; + use crate::swarm::registry::Registry; use crate::swarm::registry::tests::the_swarm_repository::returning_torrent_entries::{ - torrent_entry_info, TorrentEntryInfo, + TorrentEntryInfo, torrent_entry_info, }; - 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, @@ -1346,11 +1347,11 @@ mod tests { use std::sync::Arc; - use torrust_tracker_primitives::peer::fixture::PeerBuilder; use torrust_tracker_primitives::DurationSinceUnixEpoch; + use torrust_tracker_primitives::peer::fixture::PeerBuilder; - use crate::event::sender::tests::{expect_event_sequence, MockEventSender}; use crate::event::Event; + use crate::event::sender::tests::{MockEventSender, expect_event_sequence}; use crate::swarm::registry::Registry; use crate::tests::sample_info_hash; diff --git a/packages/test-helpers/src/random.rs b/packages/test-helpers/src/random.rs index 62265dbd7..14cc56498 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, RngExt}; +use rand::{RngExt, rng}; /// Returns a random alphanumeric string of a certain size. /// diff --git a/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs b/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs index 4deb1955a..5a8094e21 100644 --- a/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs +++ b/packages/torrent-repository-benchmarking/benches/helpers/asyn.rs @@ -5,7 +5,7 @@ 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}; +use super::utils::{DEFAULT_PEER, generate_unique_info_hashes}; pub async fn add_one_torrent(samples: u64) -> Duration where diff --git a/packages/torrent-repository-benchmarking/benches/helpers/sync.rs b/packages/torrent-repository-benchmarking/benches/helpers/sync.rs index 2cefb5a4a..59a5bdfc3 100644 --- a/packages/torrent-repository-benchmarking/benches/helpers/sync.rs +++ b/packages/torrent-repository-benchmarking/benches/helpers/sync.rs @@ -5,7 +5,7 @@ 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}; +use super::utils::{DEFAULT_PEER, generate_unique_info_hashes}; // Simply add one torrent #[must_use] diff --git a/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs b/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs index f5f8e4b28..058058d73 100644 --- a/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs +++ b/packages/torrent-repository-benchmarking/benches/repository_benchmark.rs @@ -2,7 +2,7 @@ use std::time::Duration; mod helpers; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use torrust_tracker_torrent_repository_benchmarking::{ TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, TorrentsRwLockTokio, TorrentsRwLockTokioMutexStd, TorrentsRwLockTokioMutexTokio, TorrentsSkipMapMutexParkingLot, TorrentsSkipMapMutexStd, diff --git a/packages/torrent-repository-benchmarking/src/entry/mod.rs b/packages/torrent-repository-benchmarking/src/entry/mod.rs index b920839d9..33ddfcba0 100644 --- a/packages/torrent-repository-benchmarking/src/entry/mod.rs +++ b/packages/torrent-repository-benchmarking/src/entry/mod.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_primitives::{DurationSinceUnixEpoch, peer}; use self::peer_list::PeerList; diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs index 738c3ff9d..c84f1233f 100644 --- a/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_parking_lot.rs @@ -3,7 +3,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_primitives::{DurationSinceUnixEpoch, peer}; use super::{Entry, EntrySync}; use crate::{EntryMutexParkingLot, EntrySingle}; diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs index 0ab70a96f..fd25e999c 100644 --- a/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_std.rs @@ -3,7 +3,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_primitives::{DurationSinceUnixEpoch, peer}; use super::{Entry, EntrySync}; use crate::{EntryMutexStd, EntrySingle}; diff --git a/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs b/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs index 6db789a72..d9e7d5191 100644 --- a/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/entry/mutex_tokio.rs @@ -3,7 +3,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_primitives::{DurationSinceUnixEpoch, peer}; use super::{Entry, EntryAsync}; use crate::{EntryMutexTokio, EntrySingle}; diff --git a/packages/torrent-repository-benchmarking/src/entry/peer_list.rs b/packages/torrent-repository-benchmarking/src/entry/peer_list.rs index 74dd7df10..a7f143c8f 100644 --- a/packages/torrent-repository-benchmarking/src/entry/peer_list.rs +++ b/packages/torrent-repository-benchmarking/src/entry/peer_list.rs @@ -2,7 +2,7 @@ use std::net::SocketAddr; use std::sync::Arc; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, PeerId}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, PeerId, peer}; // code-review: the current implementation uses the peer Id as the ``BTreeMap`` // key. That would allow adding two identical peers except for the Id. 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 index ac0dc0b30..e6f937a09 100644 --- a/packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs +++ b/packages/torrent-repository-benchmarking/src/entry/rw_lock_parking_lot.rs @@ -3,7 +3,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_primitives::{DurationSinceUnixEpoch, peer}; use super::{Entry, EntrySync}; use crate::{EntryRwLockParkingLot, EntrySingle}; 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 fec94b4a5..1ee682c60 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use super::Repository; use crate::entry::peer_list::PeerList; @@ -29,10 +29,9 @@ where 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 + match self.torrents.get(info_hash) { + Some(entry) => entry.upsert_peer(peer), + _ => false, } } } diff --git a/packages/torrent-repository-benchmarking/src/repository/mod.rs b/packages/torrent-repository-benchmarking/src/repository/mod.rs index cf58838a1..aca94629f 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; pub mod dash_map_mutex_std; pub mod rw_lock_std; 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 5000579dd..57a2416f1 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_std.rs @@ -2,11 +2,11 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; 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_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use super::Repository; -use crate::entry::peer_list::PeerList; use crate::entry::Entry; +use crate::entry::peer_list::PeerList; use crate::{EntrySingle, TorrentsRwLockStd}; #[derive(Default, Debug)] 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 085256ff1..762f3b211 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use super::Repository; use crate::entry::peer_list::PeerList; 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 9fd451149..b2ace0e76 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; 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 e85200aeb..17cbd3174 100644 --- a/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs +++ b/packages/torrent-repository-benchmarking/src/repository/rw_lock_tokio.rs @@ -2,11 +2,11 @@ use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::TrackerPolicy; 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_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use super::RepositoryAsync; -use crate::entry::peer_list::PeerList; use crate::entry::Entry; +use crate::entry::peer_list::PeerList; use crate::{EntrySingle, TorrentsRwLockTokio}; #[derive(Default, Debug)] 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 8d6584713..1932d46f8 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; 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 c8f499e03..cb057124c 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use super::RepositoryAsync; use crate::entry::peer_list::PeerList; 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 0432b13d0..67d3dfb82 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use super::Repository; use crate::entry::peer_list::PeerList; diff --git a/packages/torrent-repository-benchmarking/tests/common/repo.rs b/packages/torrent-repository-benchmarking/tests/common/repo.rs index 2987240ef..d2c686b85 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::{AggregateActiveSwarmMetadata, SwarmMetadata}; -use torrust_tracker_primitives::{peer, DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap}; +use torrust_tracker_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use torrust_tracker_torrent_repository_benchmarking::repository::{Repository as _, RepositoryAsync as _}; use torrust_tracker_torrent_repository_benchmarking::{ EntrySingle, TorrentsDashMapMutexStd, TorrentsRwLockStd, TorrentsRwLockStdMutexStd, TorrentsRwLockStdMutexTokio, diff --git a/packages/torrent-repository-benchmarking/tests/common/torrent.rs b/packages/torrent-repository-benchmarking/tests/common/torrent.rs index 02874f9fc..335089203 100644 --- a/packages/torrent-repository-benchmarking/tests/common/torrent.rs +++ b/packages/torrent-repository-benchmarking/tests/common/torrent.rs @@ -3,7 +3,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_primitives::{DurationSinceUnixEpoch, peer}; use torrust_tracker_torrent_repository_benchmarking::entry::{Entry as _, EntryAsync as _, EntrySync as _}; use torrust_tracker_torrent_repository_benchmarking::{ EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, diff --git a/packages/torrent-repository-benchmarking/tests/entry/mod.rs b/packages/torrent-repository-benchmarking/tests/entry/mod.rs index 4293cdb57..6acc34399 100644 --- a/packages/torrent-repository-benchmarking/tests/entry/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/entry/mod.rs @@ -4,16 +4,16 @@ 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_configuration::{TORRENT_PEERS_LIMIT, TrackerPolicy}; use torrust_tracker_primitives::peer::Peer; -use torrust_tracker_primitives::{peer, AnnounceEvent, NumberOfBytes}; +use torrust_tracker_primitives::{AnnounceEvent, NumberOfBytes, peer}; use torrust_tracker_torrent_repository_benchmarking::{ EntryMutexParkingLot, EntryMutexStd, EntryMutexTokio, EntryRwLockParkingLot, EntrySingle, }; +use crate::CurrentClock; use crate::common::torrent::Torrent; use crate::common::torrent_peer_builder::{a_completed_peer, a_started_peer}; -use crate::CurrentClock; #[fixture] fn single() -> Torrent { diff --git a/packages/torrent-repository-benchmarking/tests/repository/mod.rs b/packages/torrent-repository-benchmarking/tests/repository/mod.rs index 72accbed1..1bd73c3e6 100644 --- a/packages/torrent-repository-benchmarking/tests/repository/mod.rs +++ b/packages/torrent-repository-benchmarking/tests/repository/mod.rs @@ -7,12 +7,12 @@ use torrust_tracker_configuration::TrackerPolicy; use torrust_tracker_primitives::pagination::Pagination; use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::{AnnounceEvent, NumberOfBytes, NumberOfDownloadsBTreeMap}; +use torrust_tracker_torrent_repository_benchmarking::EntrySingle; 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}; diff --git a/packages/tracker-client/src/http/client/requests/announce.rs b/packages/tracker-client/src/http/client/requests/announce.rs index 04ceddbe9..4ebdae97c 100644 --- a/packages/tracker-client/src/http/client/requests/announce.rs +++ b/packages/tracker-client/src/http/client/requests/announce.rs @@ -6,7 +6,7 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_udp_tracker_protocol::PeerId; use serde_repr::Serialize_repr; -use crate::http::{percent_encode_byte_array, ByteArray20}; +use crate::http::{ByteArray20, percent_encode_byte_array}; use crate::peer_id::default_production_peer_id; pub struct Query { diff --git a/packages/tracker-client/src/http/client/requests/scrape.rs b/packages/tracker-client/src/http/client/requests/scrape.rs index 823df352a..9700bd34b 100644 --- a/packages/tracker-client/src/http/client/requests/scrape.rs +++ b/packages/tracker-client/src/http/client/requests/scrape.rs @@ -4,7 +4,7 @@ use std::str::FromStr; use bittorrent_primitives::info_hash::InfoHash; -use crate::http::{percent_encode_byte_array, ByteArray20}; +use crate::http::{ByteArray20, percent_encode_byte_array}; pub struct Query { pub info_hash: Vec, diff --git a/packages/tracker-client/src/peer_id.rs b/packages/tracker-client/src/peer_id.rs index 1773f7edd..5afcf7b09 100644 --- a/packages/tracker-client/src/peer_id.rs +++ b/packages/tracker-client/src/peer_id.rs @@ -40,7 +40,7 @@ fn random_suffix_12_digits() -> String { #[cfg(test)] mod tests { - use super::{default_production_peer_id, DEFAULT_TEST_PEER_ID}; + use super::{DEFAULT_TEST_PEER_ID, default_production_peer_id}; #[test] fn default_test_peer_id_should_use_rc_prefix_and_3000_version() { diff --git a/packages/tracker-client/src/udp/mod.rs b/packages/tracker-client/src/udp/mod.rs index 7694fb88b..c60a94bd5 100644 --- a/packages/tracker-client/src/udp/mod.rs +++ b/packages/tracker-client/src/udp/mod.rs @@ -82,7 +82,7 @@ mod tests { fn it_should_display_unrecognized_udp_tracker_response_without_debug_noise() { // Arrange let error = Error::UnableToParseResponse { - err: Arc::new(io::Error::new(io::ErrorKind::Other, "failed to fill whole buffer")), + err: Arc::new(io::Error::other("failed to fill whole buffer")), response: vec![0, 0, 0, 1], }; diff --git a/packages/tracker-core/src/announce_handler.rs b/packages/tracker-core/src/announce_handler.rs index df1f107a2..d6d32ac59 100644 --- a/packages/tracker-core/src/announce_handler.rs +++ b/packages/tracker-core/src/announce_handler.rs @@ -95,7 +95,7 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_configuration::{Core, TORRENT_PEERS_LIMIT}; -use torrust_tracker_primitives::{peer, AnnounceData, NumberOfDownloads}; +use torrust_tracker_primitives::{AnnounceData, NumberOfDownloads, peer}; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::databases; @@ -345,10 +345,10 @@ mod tests { use std::sync::Arc; + use crate::announce_handler::PeersWanted; use crate::announce_handler::tests::the_announce_handler::{ peer_ip, public_tracker, sample_peer_1, sample_peer_2, sample_peer_3, }; - use crate::announce_handler::PeersWanted; use crate::test_helpers::tests::{sample_info_hash, sample_peer}; mod should_assign_the_ip_to_the_peer { @@ -394,8 +394,8 @@ mod tests { } #[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( - ) { + 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 = @@ -436,8 +436,8 @@ mod tests { } #[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( - ) { + 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()); @@ -529,8 +529,8 @@ mod tests { mod it_should_update_the_swarm_stats_for_the_torrent { - use crate::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker}; use crate::announce_handler::PeersWanted; + use crate::announce_handler::tests::the_announce_handler::{peer_ip, public_tracker}; use crate::test_helpers::tests::{completed_peer, leecher, sample_info_hash, seeder, started_peer}; #[tokio::test] diff --git a/packages/tracker-core/src/authentication/handler.rs b/packages/tracker-core/src/authentication/handler.rs index 0c42e350c..6410847cd 100644 --- a/packages/tracker-core/src/authentication/handler.rs +++ b/packages/tracker-core/src/authentication/handler.rs @@ -15,7 +15,7 @@ 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 super::{CurrentClock, Key, PeerKey, key}; use crate::databases; use crate::error::PeerKeyError; @@ -333,8 +333,8 @@ mod tests { 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; + 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() { @@ -360,15 +360,15 @@ mod tests { use torrust_tracker_clock::clock::stopped::Stopped; use torrust_tracker_clock::clock::{self, Time}; + use crate::CurrentClock; + use crate::authentication::PeerKey; + use crate::authentication::handler::AddKeyRequest; use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ instantiate_keys_handler, instantiate_keys_handler_with_database, mock_auth_key_store, }; - use crate::authentication::handler::AddKeyRequest; - use crate::authentication::PeerKey; use crate::databases::driver::Driver; use crate::databases::{self, AuthKeyStore}; use crate::error::PeerKeyError; - use crate::CurrentClock; #[tokio::test] async fn it_should_add_a_randomly_generated_key() { @@ -434,15 +434,15 @@ mod tests { use torrust_tracker_clock::clock::stopped::Stopped; use torrust_tracker_clock::clock::{self, Time}; + use crate::CurrentClock; + use crate::authentication::handler::AddKeyRequest; use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ instantiate_keys_handler, instantiate_keys_handler_with_database, mock_auth_key_store, }; - use crate::authentication::handler::AddKeyRequest; use crate::authentication::{Key, PeerKey}; use crate::databases::driver::Driver; use crate::databases::{self, AuthKeyStore}; use crate::error::PeerKeyError; - use crate::CurrentClock; #[tokio::test] async fn it_should_add_a_pre_generated_key() { @@ -542,11 +542,11 @@ mod tests { use mockall::predicate::function; + use crate::authentication::PeerKey; + use crate::authentication::handler::AddKeyRequest; use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ instantiate_keys_handler, instantiate_keys_handler_with_database, mock_auth_key_store, }; - use crate::authentication::handler::AddKeyRequest; - use crate::authentication::PeerKey; use crate::databases::driver::Driver; use crate::databases::{self, AuthKeyStore}; use crate::error::PeerKeyError; @@ -612,10 +612,10 @@ mod tests { use mockall::predicate; + use crate::authentication::handler::AddKeyRequest; use crate::authentication::handler::tests::the_keys_handler_when_the_tracker_is_configured_as_private::{ instantiate_keys_handler, instantiate_keys_handler_with_database, mock_auth_key_store, }; - use crate::authentication::handler::AddKeyRequest; use crate::authentication::{Key, PeerKey}; use crate::databases::driver::Driver; use crate::databases::{self, AuthKeyStore}; diff --git a/packages/tracker-core/src/authentication/key/peer_key.rs b/packages/tracker-core/src/authentication/key/peer_key.rs index ba648ad2f..6e9dfdf98 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, RngExt}; +use rand::{RngExt, rng}; 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/authentication/key/repository/in_memory.rs b/packages/tracker-core/src/authentication/key/repository/in_memory.rs index 5911771d4..b1201e148 100644 --- a/packages/tracker-core/src/authentication/key/repository/in_memory.rs +++ b/packages/tracker-core/src/authentication/key/repository/in_memory.rs @@ -90,9 +90,9 @@ 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; + use crate::authentication::key::Key; + use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; #[tokio::test] async fn insert_a_new_peer_key() { diff --git a/packages/tracker-core/src/authentication/mod.rs b/packages/tracker-core/src/authentication/mod.rs index ba793ecf0..a2bc08d79 100644 --- a/packages/tracker-core/src/authentication/mod.rs +++ b/packages/tracker-core/src/authentication/mod.rs @@ -33,8 +33,8 @@ mod tests { 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_configuration::v2_0_0::core::PrivateMode; use torrust_tracker_test_helpers::configuration; use crate::authentication::handler::KeysHandler; @@ -50,8 +50,8 @@ mod tests { instantiate_keys_manager_and_authentication_with_configuration(&config).await } - async fn instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled( - ) -> (Arc, Arc) { + async fn instantiate_keys_manager_and_authentication_with_checking_keys_expiration_disabled() + -> (Arc, Arc) { let mut config = configuration::ephemeral_private(); config.core.private_mode = Some(PrivateMode { @@ -118,11 +118,11 @@ mod tests { mod randomly_generated_keys { use std::time::Duration; + use crate::authentication::Key; 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::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { @@ -156,12 +156,12 @@ mod tests { mod pre_generated_keys { + use crate::authentication::Key; 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::authentication::Key; #[tokio::test] async fn it_should_authenticate_a_peer_with_the_key() { @@ -216,9 +216,9 @@ mod tests { } mod pre_generated_keys { + use crate::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/packages/tracker-core/src/authentication/service.rs b/packages/tracker-core/src/authentication/service.rs index 75b28944f..e9d145602 100644 --- a/packages/tracker-core/src/authentication/service.rs +++ b/packages/tracker-core/src/authentication/service.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; use super::key::repository::in_memory::InMemoryKeyRepository; -use super::{key, Error, Key}; +use super::{Error, Key, key}; /// The authentication service responsible for validating peer keys. /// @@ -157,8 +157,8 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use torrust_tracker_configuration::Core; + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::authentication::service::AuthenticationService; @@ -238,8 +238,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 { @@ -272,8 +272,8 @@ mod tests { use std::sync::Arc; use std::time::Duration; - use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use torrust_tracker_configuration::Core; + use torrust_tracker_configuration::v2_0_0::core::PrivateMode; use crate::authentication::key::repository::in_memory::InMemoryKeyRepository; use crate::authentication::service::AuthenticationService; diff --git a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/database/mod.rs b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/database/mod.rs index 582f68d21..7a616f75d 100644 --- a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/database/mod.rs +++ b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/database/mod.rs @@ -1,10 +1,10 @@ use std::path::PathBuf; use std::time::Duration; -use anyhow::{anyhow, Context, Result}; +use anyhow::{Context, Result, anyhow}; +use bittorrent_tracker_core::databases::SchemaMigrator; use bittorrent_tracker_core::databases::driver::Driver; use bittorrent_tracker_core::databases::setup::DatabaseStores; -use bittorrent_tracker_core::databases::SchemaMigrator; use testcontainers::{ContainerAsync, GenericImage}; mod mysql; diff --git a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/keys.rs b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/keys.rs index 6e548aa0a..b1308a190 100644 --- a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/keys.rs +++ b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/keys.rs @@ -2,8 +2,8 @@ use anyhow::{Context, Result}; use bittorrent_tracker_core::authentication; use bittorrent_tracker_core::databases::AuthKeyStore; -use super::super::sampling::measure_operation_async; use super::super::RawOperationSamples; +use super::super::sampling::measure_operation_async; /// Benchmarks authentication-key persistence operations. /// diff --git a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/torrent.rs b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/torrent.rs index 7c71624a1..dd86a2a0a 100644 --- a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/torrent.rs +++ b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/torrent.rs @@ -1,8 +1,8 @@ use anyhow::{Context, Result}; use bittorrent_tracker_core::databases::TorrentMetricsStore; -use super::super::sampling::{downloads_from_index, info_hash_from_index, measure_operation_async}; use super::super::RawOperationSamples; +use super::super::sampling::{downloads_from_index, info_hash_from_index, measure_operation_async}; /// Benchmarks torrent statistics persistence operations. /// diff --git a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/whitelist.rs b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/whitelist.rs index bd9b780be..0e1c0e4ad 100644 --- a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/whitelist.rs +++ b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/operations/whitelist.rs @@ -1,8 +1,8 @@ use anyhow::{Context, Result}; use bittorrent_tracker_core::databases::WhitelistStore; -use super::super::sampling::{info_hash_from_index, measure_operation_async}; use super::super::RawOperationSamples; +use super::super::sampling::{info_hash_from_index, measure_operation_async}; /// Benchmarks whitelist-related persistence operations. /// diff --git a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/sampling.rs b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/sampling.rs index a0daf9b00..78b5a1784 100644 --- a/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/sampling.rs +++ b/packages/tracker-core/src/bin/persistence_benchmark/driver_bench/sampling.rs @@ -1,7 +1,7 @@ use std::str::FromStr; use std::time::Instant; -use anyhow::{anyhow, Context, Result}; +use anyhow::{Context, Result, anyhow}; use bittorrent_primitives::info_hash::InfoHash; use super::RawOperationSamples; diff --git a/packages/tracker-core/src/bin/persistence_benchmark/metrics.rs b/packages/tracker-core/src/bin/persistence_benchmark/metrics.rs index 89e2d1049..3cb7994d0 100644 --- a/packages/tracker-core/src/bin/persistence_benchmark/metrics.rs +++ b/packages/tracker-core/src/bin/persistence_benchmark/metrics.rs @@ -1,6 +1,6 @@ use std::time::Duration; -use anyhow::{anyhow, Result}; +use anyhow::{Result, anyhow}; use super::driver_bench::RawOperationSamples; diff --git a/packages/tracker-core/src/bin/persistence_benchmark/report.rs b/packages/tracker-core/src/bin/persistence_benchmark/report.rs index 9ea74d431..b6f0dfc72 100644 --- a/packages/tracker-core/src/bin/persistence_benchmark/report.rs +++ b/packages/tracker-core/src/bin/persistence_benchmark/report.rs @@ -99,7 +99,7 @@ fn duration_to_micros(duration: std::time::Duration) -> u64 { mod tests { use std::time::Duration; - use super::{to_json_pretty, BenchReport, ReportMeta, ReportTimings}; + use super::{BenchReport, ReportMeta, ReportTimings, to_json_pretty}; use crate::persistence_benchmark::metrics::OperationStats; #[test] diff --git a/packages/tracker-core/src/container.rs b/packages/tracker-core/src/container.rs index e52547c28..d73859cc0 100644 --- a/packages/tracker-core/src/container.rs +++ b/packages/tracker-core/src/container.rs @@ -8,7 +8,7 @@ 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, DatabaseStores}; +use crate::databases::setup::{DatabaseStores, initialize_database}; use crate::scrape_handler::ScrapeHandler; use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::torrent::manager::TorrentsManager; diff --git a/packages/tracker-core/src/databases/driver/mod.rs b/packages/tracker-core/src/databases/driver/mod.rs index bc1fa7926..39cf7d75f 100644 --- a/packages/tracker-core/src/databases/driver/mod.rs +++ b/packages/tracker-core/src/databases/driver/mod.rs @@ -96,11 +96,11 @@ pub(crate) mod tests { } async fn create_database_tables(driver: &Arc>) -> Result<(), Box> { - for _ in 0..5 { + for _ in 0..20 { if driver.create_database_tables().await.is_ok() { return Ok(()); } - tokio::time::sleep(Duration::from_secs(2)).await; + tokio::time::sleep(Duration::from_secs(3)).await; } Err("Database is not ready after retries.".into()) } diff --git a/packages/tracker-core/src/databases/driver/mysql/auth_key_store.rs b/packages/tracker-core/src/databases/driver/mysql/auth_key_store.rs index 6029855c2..f9faca074 100644 --- a/packages/tracker-core/src/databases/driver/mysql/auth_key_store.rs +++ b/packages/tracker-core/src/databases/driver/mysql/auth_key_store.rs @@ -2,10 +2,10 @@ use ::sqlx::Row; use async_trait::async_trait; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use super::{Mysql, DRIVER}; +use super::{DRIVER, Mysql}; use crate::authentication::{self, Key}; -use crate::databases::error::Error; use crate::databases::AuthKeyStore; +use crate::databases::error::Error; #[async_trait] impl AuthKeyStore for Mysql { diff --git a/packages/tracker-core/src/databases/driver/mysql/mod.rs b/packages/tracker-core/src/databases/driver/mysql/mod.rs index 1af4aaef9..ce2d376c4 100644 --- a/packages/tracker-core/src/databases/driver/mysql/mod.rs +++ b/packages/tracker-core/src/databases/driver/mysql/mod.rs @@ -78,7 +78,7 @@ impl Mysql { mod tests { use std::sync::Arc; - use testcontainers::core::IntoContainerPort; + use testcontainers::core::{IntoContainerPort, WaitFor}; /* We run a MySQL container and run all the tests against the same container and database. @@ -114,8 +114,12 @@ mod tests { let container = GenericImage::new("mysql", image_tag.as_str()) .with_exposed_port(config.internal_port.tcp()) - // todo: this does not work - //.with_wait_for(WaitFor::message_on_stdout("ready for connections")) + // MySQL 8.0 outputs "ready for connections" to stderr (not stdout). + // The first occurrence is during internal init (port: 0); the second + // includes "port: 3306" and indicates the server is ready for TCP + // connections. We wait for the second message to avoid connecting + // before MySQL accepts client traffic. + .with_wait_for(WaitFor::message_on_stderr("port: 3306")) .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", "%") diff --git a/packages/tracker-core/src/databases/driver/mysql/schema_migrator.rs b/packages/tracker-core/src/databases/driver/mysql/schema_migrator.rs index 77c620a84..422c50681 100644 --- a/packages/tracker-core/src/databases/driver/mysql/schema_migrator.rs +++ b/packages/tracker-core/src/databases/driver/mysql/schema_migrator.rs @@ -1,10 +1,10 @@ use async_trait::async_trait; -use sqlx::migrate::Migrate; use sqlx::MySqlPool; +use sqlx::migrate::Migrate; -use super::{Mysql, DRIVER, MIGRATOR}; -use crate::databases::error::Error; +use super::{DRIVER, MIGRATOR, Mysql}; use crate::databases::SchemaMigrator; +use crate::databases::error::Error; /// The four tables created by the three pre-v4 manual migrations. /// diff --git a/packages/tracker-core/src/databases/driver/mysql/torrent_metrics_store.rs b/packages/tracker-core/src/databases/driver/mysql/torrent_metrics_store.rs index 1f8d7f436..764d1c68c 100644 --- a/packages/tracker-core/src/databases/driver/mysql/torrent_metrics_store.rs +++ b/packages/tracker-core/src/databases/driver/mysql/torrent_metrics_store.rs @@ -5,10 +5,10 @@ use async_trait::async_trait; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; -use super::{Mysql, DRIVER}; +use super::{DRIVER, Mysql}; +use crate::databases::TorrentMetricsStore; use crate::databases::driver::TORRENTS_DOWNLOADS_TOTAL; use crate::databases::error::Error; -use crate::databases::TorrentMetricsStore; #[async_trait] impl TorrentMetricsStore for Mysql { diff --git a/packages/tracker-core/src/databases/driver/mysql/whitelist_store.rs b/packages/tracker-core/src/databases/driver/mysql/whitelist_store.rs index 71c1ac7bd..8405c7101 100644 --- a/packages/tracker-core/src/databases/driver/mysql/whitelist_store.rs +++ b/packages/tracker-core/src/databases/driver/mysql/whitelist_store.rs @@ -5,9 +5,9 @@ use ::sqlx::Row; use async_trait::async_trait; use bittorrent_primitives::info_hash::InfoHash; -use super::{Mysql, DRIVER}; -use crate::databases::error::Error; +use super::{DRIVER, Mysql}; use crate::databases::WhitelistStore; +use crate::databases::error::Error; #[async_trait] impl WhitelistStore for Mysql { diff --git a/packages/tracker-core/src/databases/driver/postgres/auth_key_store.rs b/packages/tracker-core/src/databases/driver/postgres/auth_key_store.rs index 604ac4608..898f44c8d 100644 --- a/packages/tracker-core/src/databases/driver/postgres/auth_key_store.rs +++ b/packages/tracker-core/src/databases/driver/postgres/auth_key_store.rs @@ -2,10 +2,10 @@ use ::sqlx::Row; use async_trait::async_trait; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use super::{Postgres, DRIVER}; +use super::{DRIVER, Postgres}; use crate::authentication::{self, Key}; -use crate::databases::error::Error; use crate::databases::AuthKeyStore; +use crate::databases::error::Error; #[async_trait] impl AuthKeyStore for Postgres { diff --git a/packages/tracker-core/src/databases/driver/postgres/schema_migrator.rs b/packages/tracker-core/src/databases/driver/postgres/schema_migrator.rs index 8c2bd0393..b1a7000dd 100644 --- a/packages/tracker-core/src/databases/driver/postgres/schema_migrator.rs +++ b/packages/tracker-core/src/databases/driver/postgres/schema_migrator.rs @@ -1,8 +1,8 @@ use async_trait::async_trait; -use super::{Postgres, DRIVER, MIGRATOR}; -use crate::databases::error::Error; +use super::{DRIVER, MIGRATOR, Postgres}; use crate::databases::SchemaMigrator; +use crate::databases::error::Error; #[async_trait] impl SchemaMigrator for Postgres { diff --git a/packages/tracker-core/src/databases/driver/postgres/torrent_metrics_store.rs b/packages/tracker-core/src/databases/driver/postgres/torrent_metrics_store.rs index d96fd2268..093de4b7a 100644 --- a/packages/tracker-core/src/databases/driver/postgres/torrent_metrics_store.rs +++ b/packages/tracker-core/src/databases/driver/postgres/torrent_metrics_store.rs @@ -5,10 +5,10 @@ use async_trait::async_trait; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; -use super::{Postgres, DRIVER}; +use super::{DRIVER, Postgres}; +use crate::databases::TorrentMetricsStore; use crate::databases::driver::TORRENTS_DOWNLOADS_TOTAL; use crate::databases::error::Error; -use crate::databases::TorrentMetricsStore; #[async_trait] impl TorrentMetricsStore for Postgres { diff --git a/packages/tracker-core/src/databases/driver/postgres/whitelist_store.rs b/packages/tracker-core/src/databases/driver/postgres/whitelist_store.rs index a8d42475f..7ed1524fd 100644 --- a/packages/tracker-core/src/databases/driver/postgres/whitelist_store.rs +++ b/packages/tracker-core/src/databases/driver/postgres/whitelist_store.rs @@ -5,9 +5,9 @@ use ::sqlx::Row; use async_trait::async_trait; use bittorrent_primitives::info_hash::InfoHash; -use super::{Postgres, DRIVER}; -use crate::databases::error::Error; +use super::{DRIVER, Postgres}; use crate::databases::WhitelistStore; +use crate::databases::error::Error; #[async_trait] impl WhitelistStore for Postgres { diff --git a/packages/tracker-core/src/databases/driver/sqlite/auth_key_store.rs b/packages/tracker-core/src/databases/driver/sqlite/auth_key_store.rs index f94770842..5a3c4486d 100644 --- a/packages/tracker-core/src/databases/driver/sqlite/auth_key_store.rs +++ b/packages/tracker-core/src/databases/driver/sqlite/auth_key_store.rs @@ -4,10 +4,10 @@ use ::sqlx::Row; use async_trait::async_trait; use torrust_tracker_primitives::DurationSinceUnixEpoch; -use super::{Sqlite, DRIVER}; +use super::{DRIVER, Sqlite}; use crate::authentication::{self, Key}; -use crate::databases::error::Error; use crate::databases::AuthKeyStore; +use crate::databases::error::Error; #[async_trait] impl AuthKeyStore for Sqlite { diff --git a/packages/tracker-core/src/databases/driver/sqlite/schema_migrator.rs b/packages/tracker-core/src/databases/driver/sqlite/schema_migrator.rs index 39650c48a..c188759a0 100644 --- a/packages/tracker-core/src/databases/driver/sqlite/schema_migrator.rs +++ b/packages/tracker-core/src/databases/driver/sqlite/schema_migrator.rs @@ -1,10 +1,10 @@ use async_trait::async_trait; -use sqlx::migrate::Migrate; use sqlx::SqlitePool; +use sqlx::migrate::Migrate; -use super::{Sqlite, DRIVER, MIGRATOR}; -use crate::databases::error::Error; +use super::{DRIVER, MIGRATOR, Sqlite}; use crate::databases::SchemaMigrator; +use crate::databases::error::Error; /// The four tables created by the three pre-v4 manual migrations. /// @@ -159,14 +159,14 @@ async fn bootstrap_legacy_schema(pool: &SqlitePool) -> Result<(), Error> { mod tests { use std::path::PathBuf; - use ::sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; use ::sqlx::SqlitePool; + use ::sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions}; use torrust_tracker_test_helpers::configuration::ephemeral_sqlite_database; - use super::{bootstrap_legacy_schema, LEGACY_TABLES}; + use super::{LEGACY_TABLES, bootstrap_legacy_schema}; + use crate::databases::SchemaMigrator; use crate::databases::driver::sqlite::Sqlite; use crate::databases::error::Error; - use crate::databases::SchemaMigrator; /// Connect to a fresh on-disk ephemeral `SQLite` database. We use a real /// file (not `:memory:`) so the same connection pool used by `Sqlite` diff --git a/packages/tracker-core/src/databases/driver/sqlite/torrent_metrics_store.rs b/packages/tracker-core/src/databases/driver/sqlite/torrent_metrics_store.rs index b8df34fb1..29c3e6a24 100644 --- a/packages/tracker-core/src/databases/driver/sqlite/torrent_metrics_store.rs +++ b/packages/tracker-core/src/databases/driver/sqlite/torrent_metrics_store.rs @@ -5,10 +5,10 @@ use async_trait::async_trait; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; -use super::{Sqlite, DRIVER}; +use super::{DRIVER, Sqlite}; +use crate::databases::TorrentMetricsStore; use crate::databases::driver::TORRENTS_DOWNLOADS_TOTAL; use crate::databases::error::Error; -use crate::databases::TorrentMetricsStore; #[async_trait] impl TorrentMetricsStore for Sqlite { diff --git a/packages/tracker-core/src/databases/driver/sqlite/whitelist_store.rs b/packages/tracker-core/src/databases/driver/sqlite/whitelist_store.rs index 263eae2fb..5e198a81b 100644 --- a/packages/tracker-core/src/databases/driver/sqlite/whitelist_store.rs +++ b/packages/tracker-core/src/databases/driver/sqlite/whitelist_store.rs @@ -5,9 +5,9 @@ use ::sqlx::Row; use async_trait::async_trait; use bittorrent_primitives::info_hash::InfoHash; -use super::{Sqlite, DRIVER}; -use crate::databases::error::Error; +use super::{DRIVER, Sqlite}; use crate::databases::WhitelistStore; +use crate::databases::error::Error; #[async_trait] impl WhitelistStore for Sqlite { diff --git a/packages/tracker-core/src/databases/error.rs b/packages/tracker-core/src/databases/error.rs index f808c529c..b4403fc09 100644 --- a/packages/tracker-core/src/databases/error.rs +++ b/packages/tracker-core/src/databases/error.rs @@ -11,8 +11,8 @@ use std::panic::Location; use std::sync::Arc; -use sqlx::migrate::MigrateError; use sqlx::Error as SqlxError; +use sqlx::migrate::MigrateError; use torrust_tracker_located_error::{DynError, LocatedError}; use super::driver::Driver; diff --git a/packages/tracker-core/src/databases/setup.rs b/packages/tracker-core/src/databases/setup.rs index 8c94c1586..a5a4c533c 100644 --- a/packages/tracker-core/src/databases/setup.rs +++ b/packages/tracker-core/src/databases/setup.rs @@ -6,10 +6,10 @@ use std::sync::Arc; use torrust_tracker_configuration::Core; +use super::driver::Driver; use super::driver::mysql::Mysql; use super::driver::postgres::Postgres; use super::driver::sqlite::Sqlite; -use super::driver::Driver; use super::traits::{AuthKeyStore, SchemaMigrator, TorrentMetricsStore, WhitelistStore}; /// A bundle of narrow-trait store references, one per persistence context. diff --git a/packages/tracker-core/src/lib.rs b/packages/tracker-core/src/lib.rs index 5d963b066..745745427 100644 --- a/packages/tracker-core/src/lib.rs +++ b/packages/tracker-core/src/lib.rs @@ -187,8 +187,8 @@ mod tests { use std::net::{IpAddr, Ipv4Addr}; use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::announce_handler::PeersWanted; use crate::test_helpers::tests::{complete_peer, incomplete_peer}; @@ -248,8 +248,8 @@ mod tests { mod handling_a_scrape_request { use bittorrent_primitives::info_hash::InfoHash; - use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::ScrapeData; + use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use crate::tests::the_tracker::initialize_handlers_for_listed_tracker; diff --git a/packages/tracker-core/src/peer_tests.rs b/packages/tracker-core/src/peer_tests.rs index 07a7ecfd8..5ca37cb86 100644 --- a/packages/tracker-core/src/peer_tests.rs +++ b/packages/tracker-core/src/peer_tests.rs @@ -4,7 +4,7 @@ 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::{peer, AnnounceEvent, NumberOfBytes, PeerId}; +use torrust_tracker_primitives::{AnnounceEvent, NumberOfBytes, PeerId, peer}; use crate::CurrentClock; diff --git a/packages/tracker-core/src/scrape_handler.rs b/packages/tracker-core/src/scrape_handler.rs index 83ffa912f..0e87227c0 100644 --- a/packages/tracker-core/src/scrape_handler.rs +++ b/packages/tracker-core/src/scrape_handler.rs @@ -62,8 +62,8 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; -use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::ScrapeData; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; use super::torrent::repository::in_memory::InMemoryTorrentRepository; use super::whitelist; diff --git a/packages/tracker-core/src/statistics/event/handler.rs b/packages/tracker-core/src/statistics/event/handler.rs index afcff4e82..820f5117b 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_swarm_coordination_registry::event::Event; +use crate::statistics::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; use crate::statistics::repository::Repository; -use crate::statistics::TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL; pub async fn handle_event( event: Event, diff --git a/packages/tracker-core/src/statistics/persisted/downloads.rs b/packages/tracker-core/src/statistics/persisted/downloads.rs index e308c0063..89ca51b2e 100644 --- a/packages/tracker-core/src/statistics/persisted/downloads.rs +++ b/packages/tracker-core/src/statistics/persisted/downloads.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use bittorrent_primitives::info_hash::InfoHash; use torrust_tracker_primitives::{NumberOfDownloads, NumberOfDownloadsBTreeMap}; -use crate::databases::error::Error; use crate::databases::TorrentMetricsStore; +use crate::databases::error::Error; /// It persists torrent metrics in a database. /// diff --git a/packages/tracker-core/src/statistics/persisted/mod.rs b/packages/tracker-core/src/statistics/persisted/mod.rs index b808d9cf2..8ad083bc7 100644 --- a/packages/tracker-core/src/statistics/persisted/mod.rs +++ b/packages/tracker-core/src/statistics/persisted/mod.rs @@ -7,8 +7,8 @@ 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 super::repository::Repository; use crate::databases; use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; diff --git a/packages/tracker-core/src/statistics/repository.rs b/packages/tracker-core/src/statistics/repository.rs index 21b1da7f2..65ed64f35 100644 --- a/packages/tracker-core/src/statistics/repository.rs +++ b/packages/tracker-core/src/statistics/repository.rs @@ -8,7 +8,7 @@ use torrust_tracker_metrics::metric_name; use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::metrics::Metrics; -use super::{describe_metrics, TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL}; +use super::{TRACKER_CORE_PERSISTENT_TORRENTS_DOWNLOADS_TOTAL, describe_metrics}; /// A repository for the torrent repository metrics. #[derive(Clone)] diff --git a/packages/tracker-core/src/torrent/manager.rs b/packages/tracker-core/src/torrent/manager.rs index 60b626328..eac37522c 100644 --- a/packages/tracker-core/src/torrent/manager.rs +++ b/packages/tracker-core/src/torrent/manager.rs @@ -8,7 +8,7 @@ use torrust_tracker_primitives::DurationSinceUnixEpoch; use super::repository::in_memory::InMemoryTorrentRepository; use crate::statistics::persisted::downloads::DatabaseDownloadsMetricRepository; -use crate::{databases, CurrentClock}; +use crate::{CurrentClock, databases}; /// The `TorrentsManager` is responsible for managing torrent entries by /// integrating persistent storage and in-memory state. It provides methods to diff --git a/packages/tracker-core/src/torrent/repository/in_memory.rs b/packages/tracker-core/src/torrent/repository/in_memory.rs index e50a82933..c4c3ed406 100644 --- a/packages/tracker-core/src/torrent/repository/in_memory.rs +++ b/packages/tracker-core/src/torrent/repository/in_memory.rs @@ -3,10 +3,10 @@ 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_configuration::{TORRENT_PEERS_LIMIT, TrackerPolicy}; 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_primitives::{DurationSinceUnixEpoch, NumberOfDownloads, NumberOfDownloadsBTreeMap, peer}; use torrust_tracker_swarm_coordination_registry::{CoordinatorHandle, Registry}; /// In-memory repository for torrent entries. diff --git a/packages/tracker-core/src/torrent/services.rs b/packages/tracker-core/src/torrent/services.rs index e3a92866f..b1df0fb92 100644 --- a/packages/tracker-core/src/torrent/services.rs +++ b/packages/tracker-core/src/torrent/services.rs @@ -206,7 +206,7 @@ pub async fn get_torrents( mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; - use torrust_tracker_primitives::{peer, AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId}; + use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId, peer}; fn sample_peer() -> peer::Peer { peer::Peer { @@ -229,7 +229,7 @@ mod tests { use crate::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::torrent::services::tests::sample_peer; - use crate::torrent::services::{get_torrent_info, Info}; + use crate::torrent::services::{Info, get_torrent_info}; #[tokio::test] async fn it_should_return_none_if_the_tracker_does_not_have_the_torrent() { @@ -278,7 +278,7 @@ mod tests { use crate::torrent::repository::in_memory::InMemoryTorrentRepository; use crate::torrent::services::tests::sample_peer; - use crate::torrent::services::{get_torrents_page, BasicInfo, Pagination}; + use crate::torrent::services::{BasicInfo, Pagination, get_torrents_page}; #[tokio::test] async fn it_should_return_an_empty_result_if_the_tracker_does_not_have_any_torrent() { @@ -417,7 +417,7 @@ mod tests { 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}; + use crate::torrent::services::{BasicInfo, get_torrents}; #[tokio::test] async fn it_should_return_an_empty_list_if_none_of_the_requested_torrents_is_found() { diff --git a/packages/tracker-core/src/whitelist/manager.rs b/packages/tracker-core/src/whitelist/manager.rs index bdef1eb81..37d3e8dee 100644 --- a/packages/tracker-core/src/whitelist/manager.rs +++ b/packages/tracker-core/src/whitelist/manager.rs @@ -142,12 +142,14 @@ 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() - .await - .unwrap() - .contains(&info_hash)); + assert!( + services + .database_whitelist + .load_from_database() + .await + .unwrap() + .contains(&info_hash) + ); } #[tokio::test] @@ -161,12 +163,14 @@ 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() - .await - .unwrap() - .contains(&info_hash)); + assert!( + !services + .database_whitelist + .load_from_database() + .await + .unwrap() + .contains(&info_hash) + ); } mod persistence { diff --git a/packages/tracker-core/tests/integration.rs b/packages/tracker-core/tests/integration.rs index 9df1dee89..374b1ba06 100644 --- a/packages/tracker-core/tests/integration.rs +++ b/packages/tracker-core/tests/integration.rs @@ -3,8 +3,8 @@ 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::swarm_metadata::SwarmMetadata; use torrust_tracker_primitives::AnnounceData; +use torrust_tracker_primitives::swarm_metadata::SwarmMetadata; #[tokio::test] async fn it_should_handle_the_announce_request() { diff --git a/packages/udp-protocol/src/request.rs b/packages/udp-protocol/src/request.rs index 5db1b8085..6e84950da 100644 --- a/packages/udp-protocol/src/request.rs +++ b/packages/udp-protocol/src/request.rs @@ -9,8 +9,8 @@ use std::io::{self, Cursor, Write}; use std::mem::size_of; use either::Either; -use zerocopy::byteorder::network_endian::I32; use zerocopy::FromBytes; +use zerocopy::byteorder::network_endian::I32; use super::announce::AnnounceRequest; use super::common::*; @@ -286,7 +286,7 @@ mod tests { for action in 0i32..4 { for max_scrape_torrents in 0..3 { for num_bytes in 0..256 { - let mut request_bytes = ::std::iter::repeat(0).take(num_bytes).collect::>(); + let mut request_bytes = ::std::iter::repeat_n(0, num_bytes).collect::>(); if let Some(action_bytes) = request_bytes.get_mut(8..12) { action_bytes.copy_from_slice(&action.to_be_bytes()) diff --git a/packages/udp-tracker-core/Cargo.toml b/packages/udp-tracker-core/Cargo.toml index d44c930aa..a9bbcfc91 100644 --- a/packages/udp-tracker-core/Cargo.toml +++ b/packages/udp-tracker-core/Cargo.toml @@ -22,7 +22,6 @@ blowfish = "0" cipher = "0.5" criterion = { version = "0.5.1", features = [ "async_tokio" ] } futures = "0" -lazy_static = "1" rand = "0" serde = "1.0.219" thiserror = "2" 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 90fc721d0..533c143c4 100644 --- a/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs +++ b/packages/udp-tracker-core/benches/udp_tracker_core_benchmark.rs @@ -2,7 +2,7 @@ mod helpers; use std::time::Duration; -use criterion::{criterion_group, criterion_main, Criterion}; +use criterion::{Criterion, criterion_group, criterion_main}; use crate::helpers::sync; diff --git a/packages/udp-tracker-core/src/connection_cookie.rs b/packages/udp-tracker-core/src/connection_cookie.rs index 785f6218c..4e282807e 100644 --- a/packages/udp-tracker-core/src/connection_cookie.rs +++ b/packages/udp-tracker-core/src/connection_cookie.rs @@ -177,7 +177,7 @@ pub fn gen_remote_fingerprint(remote_addr: &SocketAddr) -> u64 { mod cookie_builder { use cipher::{BlockCipherDecrypt, BlockCipherEncrypt}; use tracing::instrument; - use zerocopy::{byteorder, IntoBytes as _, NativeEndian}; + use zerocopy::{IntoBytes as _, NativeEndian, byteorder}; pub type CookiePlainText = CipherArrayBlowfish; pub type CookieCipherText = CipherArrayBlowfish; diff --git a/packages/udp-tracker-core/src/container.rs b/packages/udp-tracker-core/src/container.rs index e6db5aec6..bb9bcb7ab 100644 --- a/packages/udp-tracker-core/src/container.rs +++ b/packages/udp-tracker-core/src/container.rs @@ -12,7 +12,7 @@ use crate::services::banning::BanService; use crate::services::connect::ConnectService; use crate::services::scrape::ScrapeService; use crate::statistics::repository::Repository; -use crate::{event, services, statistics, MAX_CONNECTION_ID_ERRORS_PER_IP}; +use crate::{MAX_CONNECTION_ID_ERRORS_PER_IP, event, services, statistics}; pub struct UdpTrackerCoreContainer { pub udp_tracker_config: Arc, 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 357bdeca5..0ae22163e 100644 --- a/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs +++ b/packages/udp-tracker-core/src/crypto/ephemeral_instance_keys.rs @@ -3,29 +3,30 @@ //! They are ephemeral because they are generated at runtime when the //! application starts and are not persisted anywhere. +use std::sync::LazyLock; + use blowfish::BlowfishLE; use cipher::{Block, KeyInit}; -use rand::rngs::ThreadRng; use rand::RngExt; +use rand::rngs::ThreadRng; pub type Seed = [u8; 32]; pub type CipherBlowfish = BlowfishLE; pub type CipherArrayBlowfish = Block; -lazy_static! { - /// The random static seed. - pub static ref RANDOM_SEED: Seed = { - let mut rng = ThreadRng::default(); - rng.random::() - }; +/// The random static seed. +pub static RANDOM_SEED: LazyLock = LazyLock::new(|| { + let mut rng = ThreadRng::default(); + rng.random::() +}); - /// The random cipher from the seed. - pub static ref RANDOM_CIPHER_BLOWFISH: CipherBlowfish = { - let mut rng = ThreadRng::default(); - let seed: Seed = rng.random(); - CipherBlowfish::new_from_slice(&seed).expect("it could not generate key") - }; +/// The random cipher from the seed. +pub static RANDOM_CIPHER_BLOWFISH: LazyLock = LazyLock::new(|| { + let mut rng = ThreadRng::default(); + let seed: Seed = rng.random(); + 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"); -} +/// The constant cipher for testing. +pub static ZEROED_TEST_CIPHER_BLOWFISH: LazyLock = + LazyLock::new(|| CipherBlowfish::new_from_slice(&[0u8; 32]).expect("it could not generate key")); diff --git a/packages/udp-tracker-core/src/crypto/keys.rs b/packages/udp-tracker-core/src/crypto/keys.rs index 2faa745c3..d87b84ccc 100644 --- a/packages/udp-tracker-core/src/crypto/keys.rs +++ b/packages/udp-tracker-core/src/crypto/keys.rs @@ -10,7 +10,7 @@ use cipher::{BlockCipherDecrypt, BlockCipherEncrypt}; use self::detail_cipher::CURRENT_CIPHER; use self::detail_seed::CURRENT_SEED; pub use crate::crypto::ephemeral_instance_keys::CipherArrayBlowfish; -use crate::crypto::ephemeral_instance_keys::{CipherBlowfish, Seed, RANDOM_CIPHER_BLOWFISH, RANDOM_SEED}; +use crate::crypto::ephemeral_instance_keys::{CipherBlowfish, RANDOM_CIPHER_BLOWFISH, RANDOM_SEED, Seed}; /// This trait is for structures that can keep and provide a seed. pub trait Keeper { @@ -107,8 +107,8 @@ mod detail_seed { #[cfg(test)] mod tests { use crate::crypto::ephemeral_instance_keys::RANDOM_SEED; - use crate::crypto::keys::detail_seed::ZEROED_TEST_SEED; use crate::crypto::keys::CURRENT_SEED; + use crate::crypto::keys::detail_seed::ZEROED_TEST_SEED; #[test] fn it_should_have_a_zero_test_seed() { diff --git a/packages/udp-tracker-core/src/lib.rs b/packages/udp-tracker-core/src/lib.rs index d6b3da635..5e2577e6d 100644 --- a/packages/udp-tracker-core/src/lib.rs +++ b/packages/udp-tracker-core/src/lib.rs @@ -22,9 +22,6 @@ pub(crate) type CurrentClock = clock::Stopped; use crypto::ephemeral_instance_keys; use tracing::instrument; -#[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; @@ -35,13 +32,13 @@ pub const UDP_TRACKER_LOG_TARGET: &str = "UDP TRACKER"; #[instrument(skip())] pub fn initialize_static() { // Initialize the Ephemeral Instance Random Seed - lazy_static::initialize(&ephemeral_instance_keys::RANDOM_SEED); + std::sync::LazyLock::force(&ephemeral_instance_keys::RANDOM_SEED); // Initialize the Ephemeral Instance Random Cipher - lazy_static::initialize(&ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH); + std::sync::LazyLock::force(&ephemeral_instance_keys::RANDOM_CIPHER_BLOWFISH); // Initialize the Zeroed Cipher - lazy_static::initialize(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); + std::sync::LazyLock::force(&ephemeral_instance_keys::ZEROED_TEST_CIPHER_BLOWFISH); } #[cfg(test)] diff --git a/packages/udp-tracker-core/src/services/announce.rs b/packages/udp-tracker-core/src/services/announce.rs index 2871ae11e..fd8f89ae3 100644 --- a/packages/udp-tracker-core/src/services/announce.rs +++ b/packages/udp-tracker-core/src/services/announce.rs @@ -16,11 +16,11 @@ 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::AnnounceRequest; +use torrust_tracker_primitives::AnnounceData; use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::ServiceBinding; -use torrust_tracker_primitives::AnnounceData; -use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; +use crate::connection_cookie::{ConnectionCookieError, check, gen_remote_fingerprint}; use crate::event::{ConnectionContext, Event}; use crate::peer_builder; diff --git a/packages/udp-tracker-core/src/services/banning.rs b/packages/udp-tracker-core/src/services/banning.rs index 8f63dd804..b83ee91fb 100644 --- a/packages/udp-tracker-core/src/services/banning.rs +++ b/packages/udp-tracker-core/src/services/banning.rs @@ -18,7 +18,7 @@ use std::collections::HashMap; use std::net::IpAddr; -use bloom::{CountingBloomFilter, ASMS}; +use bloom::{ASMS, CountingBloomFilter}; use tokio::time::Instant; use crate::UDP_TRACKER_LOG_TARGET; diff --git a/packages/udp-tracker-core/src/services/connect.rs b/packages/udp-tracker-core/src/services/connect.rs index 585e6c88c..0c01013b5 100644 --- a/packages/udp-tracker-core/src/services/connect.rs +++ b/packages/udp-tracker-core/src/services/connect.rs @@ -70,8 +70,8 @@ mod tests { 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, + MockUdpCoreStatsEventSender, 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, }; #[tokio::test] diff --git a/packages/udp-tracker-core/src/services/scrape.rs b/packages/udp-tracker-core/src/services/scrape.rs index 77fa212e5..10cc5c1ce 100644 --- a/packages/udp-tracker-core/src/services/scrape.rs +++ b/packages/udp-tracker-core/src/services/scrape.rs @@ -15,10 +15,10 @@ use bittorrent_primitives::info_hash::InfoHash; use bittorrent_tracker_core::error::{ScrapeError, WhitelistError}; use bittorrent_tracker_core::scrape_handler::ScrapeHandler; use bittorrent_udp_tracker_protocol::ScrapeRequest; -use torrust_tracker_primitives::service_binding::ServiceBinding; use torrust_tracker_primitives::ScrapeData; +use torrust_tracker_primitives::service_binding::ServiceBinding; -use crate::connection_cookie::{check, gen_remote_fingerprint, ConnectionCookieError}; +use crate::connection_cookie::{ConnectionCookieError, check, gen_remote_fingerprint}; use crate::event::{ConnectionContext, Event}; /// The `ScrapeService` is responsible for handling the `scrape` requests. diff --git a/packages/udp-tracker-core/src/statistics/event/handler.rs b/packages/udp-tracker-core/src/statistics/event/handler.rs index e5d2b87a7..14be65bdc 100644 --- a/packages/udp-tracker-core/src/statistics/event/handler.rs +++ b/packages/udp-tracker-core/src/statistics/event/handler.rs @@ -3,8 +3,8 @@ 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::UDP_TRACKER_CORE_REQUESTS_RECEIVED_TOTAL; +use crate::statistics::repository::Repository; /// # Panics /// @@ -21,7 +21,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } Event::UdpAnnounce { connection: context, .. } => { let mut label_set = LabelSet::from(context); @@ -33,7 +33,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } Event::UdpScrape { connection: context } => { let mut label_set = LabelSet::from(context); @@ -45,7 +45,7 @@ pub async fn handle_event(event: Event, stats_repository: &Repository, now: Dura { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } } @@ -60,11 +60,11 @@ mod tests { use torrust_tracker_primitives::peer::PeerAnnouncement; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::CurrentClock; 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] async fn should_increase_the_udp4_connections_counter_when_it_receives_a_udp4_connect_event() { diff --git a/packages/udp-tracker-core/src/statistics/services.rs b/packages/udp-tracker-core/src/statistics/services.rs index 18a80bad1..2144894f9 100644 --- a/packages/udp-tracker-core/src/statistics/services.rs +++ b/packages/udp-tracker-core/src/statistics/services.rs @@ -84,7 +84,7 @@ mod tests { use crate::statistics::describe_metrics; use crate::statistics::repository::Repository; - use crate::statistics::services::{get_metrics, TrackerMetrics}; + use crate::statistics::services::{TrackerMetrics, get_metrics}; #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { diff --git a/packages/udp-tracker-server/src/banning/event/handler.rs b/packages/udp-tracker-server/src/banning/event/handler.rs index 4876323a8..78f7a96e8 100644 --- a/packages/udp-tracker-server/src/banning/event/handler.rs +++ b/packages/udp-tracker-server/src/banning/event/handler.rs @@ -7,8 +7,8 @@ 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; +use crate::statistics::repository::Repository; pub async fn handle_event( event: Event, diff --git a/packages/udp-tracker-server/src/banning/event/listener.rs b/packages/udp-tracker-server/src/banning/event/listener.rs index 0d579f912..9b9261962 100644 --- a/packages/udp-tracker-server/src/banning/event/listener.rs +++ b/packages/udp-tracker-server/src/banning/event/listener.rs @@ -1,7 +1,7 @@ use std::sync::Arc; -use bittorrent_udp_tracker_core::services::banning::BanService; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use bittorrent_udp_tracker_core::services::banning::BanService; use tokio::sync::RwLock; use tokio::task::JoinHandle; use tokio_util::sync::CancellationToken; @@ -9,9 +9,9 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; use super::handler::handle_event; +use crate::CurrentClock; use crate::event::receiver::Receiver; use crate::statistics::repository::Repository; -use crate::CurrentClock; #[must_use] pub fn run_event_listener( diff --git a/packages/udp-tracker-server/src/environment.rs b/packages/udp-tracker-server/src/environment.rs index 36c5dcd1d..d4be95d06 100644 --- a/packages/udp-tracker-server/src/environment.rs +++ b/packages/udp-tracker-server/src/environment.rs @@ -6,13 +6,13 @@ 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_configuration::{Configuration, DEFAULT_TIMEOUT, logging}; use torrust_tracker_swarm_coordination_registry::container::SwarmCoordinationRegistryContainer; use crate::container::UdpTrackerServerContainer; +use crate::server::Server; use crate::server::spawner::Spawner; use crate::server::states::{Running, Stopped}; -use crate::server::Server; pub type Started = Environment; diff --git a/packages/udp-tracker-server/src/handlers/announce.rs b/packages/udp-tracker-server/src/handlers/announce.rs index 794001792..1e9e80ed9 100644 --- a/packages/udp-tracker-server/src/handlers/announce.rs +++ b/packages/udp-tracker-server/src/handlers/announce.rs @@ -10,9 +10,9 @@ use bittorrent_udp_tracker_protocol::{ Port, Response, ResponsePeer, TransactionId, }; use torrust_tracker_configuration::Core; -use torrust_tracker_primitives::service_binding::ServiceBinding; use torrust_tracker_primitives::AnnounceData; -use tracing::{instrument, Level}; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tracing::{Level, instrument}; use zerocopy::byteorder::network_endian::I32; use crate::error::Error; @@ -224,9 +224,10 @@ pub(crate) mod tests { use crate::handlers::announce::tests::announce_request::AnnounceRequestBuilder; use crate::handlers::handle_announce; use crate::handlers::tests::{ + CoreTrackerServices, CoreUdpTrackerServices, MockUdpServerStatsEventSender, 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, + sample_issue_time, }; #[tokio::test] @@ -318,8 +319,8 @@ pub(crate) mod tests { } #[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( - ) { + 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." @@ -565,9 +566,9 @@ pub(crate) mod 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, + MockUdpServerStatsEventSender, 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, + sample_issue_time, }; #[tokio::test] @@ -663,8 +664,8 @@ pub(crate) mod tests { } #[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( - ) { + 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." @@ -860,8 +861,8 @@ pub(crate) mod 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, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, - TrackerConfigurationBuilder, + MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, TrackerConfigurationBuilder, + sample_cookie_valid_range, sample_issue_time, }; use crate::tests::{announce_events_match, sample_peer}; diff --git a/packages/udp-tracker-server/src/handlers/connect.rs b/packages/udp-tracker-server/src/handlers/connect.rs index 0d69f2472..acb8fc7a9 100644 --- a/packages/udp-tracker-server/src/handlers/connect.rs +++ b/packages/udp-tracker-server/src/handlers/connect.rs @@ -5,7 +5,7 @@ use std::sync::Arc; use bittorrent_udp_tracker_core::services::connect::ConnectService; use bittorrent_udp_tracker_protocol::{ConnectRequest, ConnectResponse, ConnectionId, Response}; use torrust_tracker_primitives::service_binding::ServiceBinding; -use tracing::{instrument, Level}; +use tracing::{Level, instrument}; use crate::event::{ConnectionContext, Event, UdpRequestKind}; @@ -69,8 +69,9 @@ mod tests { 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, - sample_ipv6_remote_addr_fingerprint, sample_issue_time, MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, + MockUdpCoreStatsEventSender, MockUdpServerStatsEventSender, 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, }; fn sample_connect_request() -> ConnectRequest { diff --git a/packages/udp-tracker-server/src/handlers/error.rs b/packages/udp-tracker-server/src/handlers/error.rs index a342de938..f7cb26392 100644 --- a/packages/udp-tracker-server/src/handlers/error.rs +++ b/packages/udp-tracker-server/src/handlers/error.rs @@ -5,7 +5,7 @@ use std::ops::Range; use bittorrent_udp_tracker_core::{self, UDP_TRACKER_LOG_TARGET}; use bittorrent_udp_tracker_protocol::{ErrorResponse, Response, TransactionId}; use torrust_tracker_primitives::service_binding::ServiceBinding; -use tracing::{instrument, Level}; +use tracing::{Level, instrument}; use uuid::Uuid; use zerocopy::byteorder::network_endian::I32; diff --git a/packages/udp-tracker-server/src/handlers/mod.rs b/packages/udp-tracker-server/src/handlers/mod.rs index 4303044d9..176255cb5 100644 --- a/packages/udp-tracker-server/src/handlers/mod.rs +++ b/packages/udp-tracker-server/src/handlers/mod.rs @@ -18,14 +18,14 @@ 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 tracing::{Level, instrument}; use uuid::Uuid; use super::RawRequest; +use crate::CurrentClock; use crate::container::UdpTrackerServerContainer; use crate::error::Error; use crate::event::UdpRequestKind; -use crate::CurrentClock; #[derive(Debug, Clone, PartialEq)] pub struct CookieTimeValues { @@ -101,10 +101,9 @@ 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::InvalidRequest { request_parse_error } = e.clone() { - request_parse_error.opt_transaction_id - } else { - None + let opt_transaction_id = match e.clone() { + Error::InvalidRequest { request_parse_error } => request_parse_error.opt_transaction_id, + _ => None, }; let response = handle_error( @@ -250,18 +249,18 @@ pub(crate) mod tests { configuration::ephemeral() } - pub(crate) async fn initialize_core_tracker_services_for_default_tracker_configuration( - ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { + pub(crate) async fn initialize_core_tracker_services_for_default_tracker_configuration() + -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { initialize_core_tracker_services(&default_testing_tracker_configuration()).await } - pub(crate) async fn initialize_core_tracker_services_for_public_tracker( - ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { + pub(crate) async fn initialize_core_tracker_services_for_public_tracker() + -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_public()).await } - pub(crate) async fn initialize_core_tracker_services_for_listed_tracker( - ) -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { + pub(crate) async fn initialize_core_tracker_services_for_listed_tracker() + -> (CoreTrackerServices, CoreUdpTrackerServices, ServerUdpTrackerServices) { initialize_core_tracker_services(&configuration::ephemeral_listed()).await } diff --git a/packages/udp-tracker-server/src/handlers/scrape.rs b/packages/udp-tracker-server/src/handlers/scrape.rs index 126e25913..c08809058 100644 --- a/packages/udp-tracker-server/src/handlers/scrape.rs +++ b/packages/udp-tracker-server/src/handlers/scrape.rs @@ -8,9 +8,9 @@ use bittorrent_udp_tracker_core::{self}; use bittorrent_udp_tracker_protocol::{ NumberOfDownloads, NumberOfPeers, Response, ScrapeRequest, ScrapeResponse, TorrentScrapeStatistics, TransactionId, }; -use torrust_tracker_primitives::service_binding::ServiceBinding; use torrust_tracker_primitives::ScrapeData; -use tracing::{instrument, Level}; +use torrust_tracker_primitives::service_binding::ServiceBinding; +use tracing::{Level, instrument}; use zerocopy::byteorder::network_endian::I32; use crate::error::Error; @@ -103,8 +103,8 @@ mod tests { 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, + CoreTrackerServices, CoreUdpTrackerServices, initialize_core_tracker_services_for_public_tracker, + sample_cookie_valid_range, sample_ipv4_remote_addr, sample_issue_time, }; fn zeroed_torrent_statistics() -> TorrentScrapeStatistics { @@ -373,8 +373,8 @@ mod tests { 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, + MockUdpServerStatsEventSender, initialize_core_tracker_services_for_default_tracker_configuration, + sample_cookie_valid_range, sample_ipv4_remote_addr, }; #[tokio::test] @@ -423,8 +423,8 @@ mod tests { 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_ipv6_remote_addr, MockUdpServerStatsEventSender, + MockUdpServerStatsEventSender, initialize_core_tracker_services_for_default_tracker_configuration, + sample_cookie_valid_range, sample_ipv6_remote_addr, }; #[tokio::test] diff --git a/packages/udp-tracker-server/src/lib.rs b/packages/udp-tracker-server/src/lib.rs index 4fe6e7934..ccf202f6c 100644 --- a/packages/udp-tracker-server/src/lib.rs +++ b/packages/udp-tracker-server/src/lib.rs @@ -680,7 +680,7 @@ pub(crate) mod tests { use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use bittorrent_udp_tracker_core::event::Event; - use torrust_tracker_primitives::{peer, AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId}; + use torrust_tracker_primitives::{AnnounceEvent, DurationSinceUnixEpoch, NumberOfBytes, PeerId, peer}; pub fn sample_peer() -> peer::Peer { peer::Peer { diff --git a/packages/udp-tracker-server/src/server/launcher.rs b/packages/udp-tracker-server/src/server/launcher.rs index 4fd3a95d9..32c6f1166 100644 --- a/packages/udp-tracker-server/src/server/launcher.rs +++ b/packages/udp-tracker-server/src/server/launcher.rs @@ -12,7 +12,7 @@ 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, Started}; +use torrust_server_lib::signals::{Halted, Started, shutdown_signal_with_message}; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; use tracing::instrument; diff --git a/packages/udp-tracker-server/src/server/mod.rs b/packages/udp-tracker-server/src/server/mod.rs index c46277e50..59a4ca385 100644 --- a/packages/udp-tracker-server/src/server/mod.rs +++ b/packages/udp-tracker-server/src/server/mod.rs @@ -59,11 +59,11 @@ mod tests { use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use torrust_server_lib::registar::Registar; - use torrust_tracker_configuration::{logging, Configuration}; + use torrust_tracker_configuration::{Configuration, logging}; use torrust_tracker_test_helpers::configuration::ephemeral_public; - use super::spawner::Spawner; use super::Server; + use super::spawner::Spawner; use crate::container::UdpTrackerServerContainer; fn initialize_global_services(configuration: &Configuration) { diff --git a/packages/udp-tracker-server/src/server/processor.rs b/packages/udp-tracker-server/src/server/processor.rs index 591cbe5aa..feeaff5b8 100644 --- a/packages/udp-tracker-server/src/server/processor.rs +++ b/packages/udp-tracker-server/src/server/processor.rs @@ -8,13 +8,13 @@ use bittorrent_udp_tracker_core::{self}; use bittorrent_udp_tracker_protocol::Response; use tokio::time::Instant; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; -use tracing::{instrument, Level}; +use tracing::{Level, instrument}; use super::bound_socket::BoundSocket; use crate::container::UdpTrackerServerContainer; use crate::event::{self, ConnectionContext, Event, UdpRequestKind}; use crate::handlers::CookieTimeValues; -use crate::{handlers, RawRequest}; +use crate::{RawRequest, handlers}; pub struct Processor { socket: Arc, diff --git a/packages/udp-tracker-server/src/server/receiver.rs b/packages/udp-tracker-server/src/server/receiver.rs index 89fbed081..5432d132b 100644 --- a/packages/udp-tracker-server/src/server/receiver.rs +++ b/packages/udp-tracker-server/src/server/receiver.rs @@ -6,8 +6,8 @@ use std::task::{Context, Poll}; use futures::Stream; -use super::bound_socket::BoundSocket; use super::RawRequest; +use super::bound_socket::BoundSocket; use crate::MAX_PACKET_SIZE; pub struct Receiver { diff --git a/packages/udp-tracker-server/src/server/request_buffer.rs b/packages/udp-tracker-server/src/server/request_buffer.rs index 9e36db4fb..3bab73537 100644 --- a/packages/udp-tracker-server/src/server/request_buffer.rs +++ b/packages/udp-tracker-server/src/server/request_buffer.rs @@ -1,6 +1,6 @@ use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; -use ringbuf::traits::{Consumer, Observer, Producer}; use ringbuf::StaticRb; +use ringbuf::traits::{Consumer, Observer, Producer}; use tokio::task::AbortHandle; /// A ring buffer for managing active UDP request abort handles. diff --git a/packages/udp-tracker-server/src/server/spawner.rs b/packages/udp-tracker-server/src/server/spawner.rs index 46916f6ae..440b7f483 100644 --- a/packages/udp-tracker-server/src/server/spawner.rs +++ b/packages/udp-tracker-server/src/server/spawner.rs @@ -4,8 +4,8 @@ use std::sync::Arc; use std::time::Duration; use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; -use derive_more::derive::Display; use derive_more::Constructor; +use derive_more::derive::Display; use tokio::sync::oneshot; use tokio::task::JoinHandle; use torrust_server_lib::signals::{Halted, Started}; diff --git a/packages/udp-tracker-server/src/server/states.rs b/packages/udp-tracker-server/src/server/states.rs index 4ad059095..f3d273f7a 100644 --- a/packages/udp-tracker-server/src/server/states.rs +++ b/packages/udp-tracker-server/src/server/states.rs @@ -3,14 +3,14 @@ use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; -use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; -use derive_more::derive::Display; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use derive_more::Constructor; +use derive_more::derive::Display; use tokio::task::JoinHandle; use torrust_server_lib::registar::{ServiceRegistration, ServiceRegistrationForm}; use torrust_server_lib::signals::{Halted, Started}; -use tracing::{instrument, Level}; +use tracing::{Level, instrument}; use super::spawner::Spawner; use super::{Server, UdpError}; 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 80b2c5701..4d56f73f9 100644 --- a/packages/udp-tracker-server/src/statistics/event/handler/error.rs +++ b/packages/udp-tracker-server/src/statistics/event/handler/error.rs @@ -70,7 +70,7 @@ async fn update_connection_id_errors_counter( { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } } } @@ -107,11 +107,11 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::CurrentClock; 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() { 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 f340fe51a..eeb4a203b 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 @@ -3,8 +3,8 @@ 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; +use crate::statistics::repository::Repository; pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match stats_repository @@ -17,7 +17,7 @@ pub async fn handle_event(context: ConnectionContext, stats_repository: &Reposit { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } #[cfg(test)] @@ -27,10 +27,10 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::CurrentClock; 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() { 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 33971926e..00e364d66 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 @@ -3,8 +3,8 @@ 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; +use crate::statistics::repository::Repository; pub async fn handle_event( context: ConnectionContext, @@ -22,7 +22,7 @@ pub async fn handle_event( tracing::debug!("Successfully increased the counter for UDP requests accepted: {}", label_set); } Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } #[cfg(test)] @@ -32,11 +32,11 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::CurrentClock; 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; #[tokio::test] async fn should_increase_the_udp4_connect_requests_counter_when_it_receives_a_udp4_request_event_of_connect_kind() { 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 10f6cad88..e85a0ad30 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 @@ -3,8 +3,8 @@ 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; +use crate::statistics::repository::Repository; pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match stats_repository @@ -17,7 +17,7 @@ pub async fn handle_event(context: ConnectionContext, stats_repository: &Reposit { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } #[cfg(test)] @@ -27,10 +27,10 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::CurrentClock; 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() { 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 148b9d8da..677fdafb9 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 @@ -3,8 +3,8 @@ 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; +use crate::statistics::repository::Repository; pub async fn handle_event(context: ConnectionContext, stats_repository: &Repository, now: DurationSinceUnixEpoch) { match stats_repository @@ -17,7 +17,7 @@ pub async fn handle_event(context: ConnectionContext, stats_repository: &Reposit { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } #[cfg(test)] @@ -27,10 +27,10 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::CurrentClock; 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() { 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 b1a046b5b..3f1f995ad 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 @@ -3,8 +3,8 @@ 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_RESPONSES_SENT_TOTAL; +use crate::statistics::repository::Repository; pub async fn handle_event( context: ConnectionContext, @@ -61,7 +61,7 @@ pub async fn handle_event( { Ok(()) => {} Err(err) => tracing::error!("Failed to increase the counter: {}", err), - }; + } } #[cfg(test)] @@ -71,11 +71,11 @@ mod tests { use torrust_tracker_clock::clock::Time; use torrust_tracker_primitives::service_binding::{Protocol, ServiceBinding}; + use crate::CurrentClock; 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; #[tokio::test] async fn should_increase_the_udp4_responses_counter_when_it_receives_a_udp4_response_event() { diff --git a/packages/udp-tracker-server/src/statistics/event/listener.rs b/packages/udp-tracker-server/src/statistics/event/listener.rs index caaf5a2bc..7366957e4 100644 --- a/packages/udp-tracker-server/src/statistics/event/listener.rs +++ b/packages/udp-tracker-server/src/statistics/event/listener.rs @@ -7,9 +7,9 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_events::receiver::RecvError; use super::handler::handle_event; +use crate::CurrentClock; use crate::event::receiver::Receiver; use crate::statistics::repository::Repository; -use crate::CurrentClock; #[must_use] pub fn run_event_listener( diff --git a/packages/udp-tracker-server/src/statistics/metrics.rs b/packages/udp-tracker-server/src/statistics/metrics.rs index e167dc5ae..be0f9ab98 100644 --- a/packages/udp-tracker-server/src/statistics/metrics.rs +++ b/packages/udp-tracker-server/src/statistics/metrics.rs @@ -384,6 +384,7 @@ mod tests { use torrust_tracker_metrics::metric_name; use super::*; + use crate::CurrentClock; use crate::statistics::{ 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, @@ -391,7 +392,6 @@ mod tests { 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() { diff --git a/packages/udp-tracker-server/src/statistics/repository.rs b/packages/udp-tracker-server/src/statistics/repository.rs index c4c995b8a..df217f3fb 100644 --- a/packages/udp-tracker-server/src/statistics/repository.rs +++ b/packages/udp-tracker-server/src/statistics/repository.rs @@ -99,20 +99,21 @@ mod tests { use torrust_tracker_metrics::metric_name; use super::*; - use crate::statistics::*; use crate::CurrentClock; + use crate::statistics::*; #[test] fn it_should_implement_default() { let repo = Repository::default(); - assert!(!std::ptr::eq(&repo.stats, &Repository::new().stats)); + let new_repo = Repository::new(); + assert!(!std::ptr::eq(&raw const repo.stats, &raw const new_repo.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)); + assert!(!std::ptr::eq(&raw const repo.stats, &raw const cloned_repo.stats)); } #[tokio::test] @@ -121,33 +122,51 @@ mod tests { 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))); + 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] @@ -729,9 +748,9 @@ mod tests { 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" - ); + 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" + ); } fn assert_server_result_matches_stored_average(results: &[f64], stats: &Metrics, labels: &LabelSet, server_name: &str) { @@ -745,12 +764,16 @@ mod tests { } 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))); + 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 { diff --git a/packages/udp-tracker-server/src/statistics/services.rs b/packages/udp-tracker-server/src/statistics/services.rs index 0eac01270..3c1f8f45b 100644 --- a/packages/udp-tracker-server/src/statistics/services.rs +++ b/packages/udp-tracker-server/src/statistics/services.rs @@ -84,7 +84,7 @@ mod tests { use crate::statistics::describe_metrics; use crate::statistics::repository::Repository; - use crate::statistics::services::{get_metrics, TrackerMetrics}; + use crate::statistics::services::{TrackerMetrics, get_metrics}; #[tokio::test] async fn the_statistics_service_should_return_the_tracker_metrics() { diff --git a/packages/udp-tracker-server/tests/server/contract.rs b/packages/udp-tracker-server/tests/server/contract.rs index 8515fcec3..5b22f52be 100644 --- a/packages/udp-tracker-server/tests/server/contract.rs +++ b/packages/udp-tracker-server/tests/server/contract.rs @@ -59,9 +59,11 @@ async fn should_return_a_bad_request_response_when_the_client_sends_an_empty_req let response = Response::parse_bytes(&response, true).unwrap(); - assert!(get_error_response_message(&response) - .unwrap() - .contains("Protocol identifier missing")); + assert!( + get_error_response_message(&response) + .unwrap() + .contains("Protocol identifier missing") + ); env.stop().await; } diff --git a/project-words.txt b/project-words.txt index 75ccd808d..e88296595 100644 --- a/project-words.txt +++ b/project-words.txt @@ -76,6 +76,7 @@ distroless dler Dmqcd dockerhub +doctest downloadedi dtolnay dylib @@ -158,6 +159,7 @@ Mebibytes metainfo middlewares millis +mktemp misresolved mmap mmdb diff --git a/src/app.rs b/src/app.rs index dc93710de..34814e858 100644 --- a/src/app.rs +++ b/src/app.rs @@ -27,13 +27,13 @@ use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::{Configuration, HttpTracker, UdpTracker}; use tracing::instrument; +use crate::CurrentClock; use crate::bootstrap::jobs::manager::JobManager; use crate::bootstrap::jobs::{ self, activity_metrics_updater, health_check_api, http_tracker, torrent_cleanup, tracker_apis, udp_tracker, }; use crate::bootstrap::{self}; use crate::container::AppContainer; -use crate::CurrentClock; pub async fn run() -> (Arc, JobManager) { let (config, app_container) = bootstrap::app::setup().await; @@ -92,8 +92,8 @@ async fn start_jobs(config: &Configuration, app_container: &Arc) - 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)) + && config.udp_trackers.as_ref().is_none_or(std::vec::Vec::is_empty) + && config.http_trackers.as_ref().is_none_or(std::vec::Vec::is_empty) { tracing::warn!("No services enabled in configuration"); } diff --git a/src/bootstrap/app.rs b/src/bootstrap/app.rs index 4671ccbfd..eb01ca439 100644 --- a/src/bootstrap/app.rs +++ b/src/bootstrap/app.rs @@ -13,7 +13,7 @@ //! 4. Initialize the domain tracker. use bittorrent_udp_tracker_core::crypto::keys::{self, Keeper as _}; use torrust_tracker_configuration::validator::Validator; -use torrust_tracker_configuration::{logging, Configuration}; +use torrust_tracker_configuration::{Configuration, logging}; use tracing::instrument; use super::config::initialize_configuration; diff --git a/src/bootstrap/jobs/activity_metrics_updater.rs b/src/bootstrap/jobs/activity_metrics_updater.rs index 9bbdc3f9b..08bc83317 100644 --- a/src/bootstrap/jobs/activity_metrics_updater.rs +++ b/src/bootstrap/jobs/activity_metrics_updater.rs @@ -6,8 +6,8 @@ use tokio::task::JoinHandle; use torrust_tracker_clock::clock::Time; use torrust_tracker_configuration::Configuration; -use crate::container::AppContainer; use crate::CurrentClock; +use crate::container::AppContainer; #[must_use] pub fn start_job(config: &Configuration, app_container: &Arc) -> JoinHandle<()> { diff --git a/src/bootstrap/jobs/health_check_api.rs b/src/bootstrap/jobs/health_check_api.rs index 7c529fadd..f9dff9d1e 100644 --- a/src/bootstrap/jobs/health_check_api.rs +++ b/src/bootstrap/jobs/health_check_api.rs @@ -16,7 +16,7 @@ use tokio::sync::oneshot; use tokio::task::JoinHandle; -use torrust_axum_health_check_api_server::{server, HEALTH_CHECK_API_LOG_TARGET}; +use torrust_axum_health_check_api_server::{HEALTH_CHECK_API_LOG_TARGET, server}; use torrust_server_lib::logging::STARTED_ON; use torrust_server_lib::registar::ServiceRegistry; use torrust_server_lib::signals::{Halted, Started}; diff --git a/src/bootstrap/jobs/http_tracker.rs b/src/bootstrap/jobs/http_tracker.rs index 6991ccac7..cbeee6e19 100644 --- a/src/bootstrap/jobs/http_tracker.rs +++ b/src/bootstrap/jobs/http_tracker.rs @@ -16,8 +16,8 @@ use std::sync::Arc; use axum_server::tls_rustls::RustlsConfig; 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; +use torrust_axum_http_tracker_server::server::{HttpServer, Launcher}; use torrust_axum_server::tsl::make_rust_tls; use torrust_server_lib::registar::ServiceRegistrationForm; use tracing::instrument; diff --git a/src/bootstrap/jobs/manager.rs b/src/bootstrap/jobs/manager.rs index 565cd7b73..b69ee4a37 100644 --- a/src/bootstrap/jobs/manager.rs +++ b/src/bootstrap/jobs/manager.rs @@ -74,14 +74,17 @@ impl JobManager { 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"); + match timeout(grace_period, job.handle).await { + Ok(result) => { + if let Err(e) = result { + warn!(job = %name, "Job return an error: {:?}", e); + } else { + info!(job = %name, "Job completed gracefully"); + } + } + _ => { + warn!(job = %name, "Job did not complete in time"); } - } else { - warn!(job = %name, "Job did not complete in time"); } } } diff --git a/src/bootstrap/jobs/torrent_cleanup.rs b/src/bootstrap/jobs/torrent_cleanup.rs index 8a3a71a44..f7ea7ea86 100644 --- a/src/bootstrap/jobs/torrent_cleanup.rs +++ b/src/bootstrap/jobs/torrent_cleanup.rs @@ -42,14 +42,14 @@ pub fn start_job(config: &Core, torrents_manager: &Arc) -> Join break; } _ = interval.tick() => { - if let Some(torrents_manager) = weak_torrents_manager.upgrade() { + match weak_torrents_manager.upgrade() { Some(torrents_manager) => { let start_time = Utc::now().time(); tracing::info!("Cleaning up torrents (executed every {} secs) ...", interval_in_secs); torrents_manager.cleanup_torrents().await; tracing::info!("Cleaned up torrents in: {} ms", (Utc::now().time() - start_time).num_milliseconds()); - } else { + } _ => { break; - } + }} } } } diff --git a/src/bootstrap/jobs/tracker_apis.rs b/src/bootstrap/jobs/tracker_apis.rs index 0debe2ce3..e269bec17 100644 --- a/src/bootstrap/jobs/tracker_apis.rs +++ b/src/bootstrap/jobs/tracker_apis.rs @@ -25,8 +25,8 @@ 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_rest_tracker_api_server::server::{ApiServer, Launcher}; use torrust_axum_server::tsl::make_rust_tls; use torrust_rest_tracker_api_core::container::TrackerHttpApiCoreContainer; use torrust_server_lib::registar::ServiceRegistrationForm; diff --git a/src/bootstrap/jobs/udp_tracker.rs b/src/bootstrap/jobs/udp_tracker.rs index 2723ad9ab..d16cbf9d0 100644 --- a/src/bootstrap/jobs/udp_tracker.rs +++ b/src/bootstrap/jobs/udp_tracker.rs @@ -8,13 +8,13 @@ //! > for the configuration options. use std::sync::Arc; -use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; use bittorrent_udp_tracker_core::UDP_TRACKER_LOG_TARGET; +use bittorrent_udp_tracker_core::container::UdpTrackerCoreContainer; 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 torrust_udp_tracker_server::server::spawner::Spawner; use tracing::instrument; /// It starts a new UDP server with the provided configuration. diff --git a/src/console/ci/compose.rs b/src/console/ci/compose.rs index 39b23affe..e1e30056c 100644 --- a/src/console/ci/compose.rs +++ b/src/console/ci/compose.rs @@ -84,15 +84,12 @@ impl DockerCompose { is_active: true, }) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!( - "docker compose up failed for file '{}' and project '{}': {}", - self.file.display(), - self.project, - String::from_utf8_lossy(&output.stderr) - ), - )) + Err(io::Error::other(format!( + "docker compose up failed for file '{}' and project '{}': {}", + self.file.display(), + self.project, + String::from_utf8_lossy(&output.stderr) + ))) } } @@ -117,14 +114,11 @@ impl DockerCompose { if status.success() { Ok(()) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!( - "docker compose build failed for file '{}' and project '{}'", - self.file.display(), - self.project, - ), - )) + Err(io::Error::other(format!( + "docker compose build failed for file '{}' and project '{}'", + self.file.display(), + self.project, + ))) } } @@ -139,15 +133,12 @@ impl DockerCompose { if output.status.success() { Ok(()) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!( - "docker compose down failed for file '{}' and project '{}': {}", - self.file.display(), - self.project, - String::from_utf8_lossy(&output.stderr) - ), - )) + Err(io::Error::other(format!( + "docker compose down failed for file '{}' and project '{}': {}", + self.file.display(), + self.project, + String::from_utf8_lossy(&output.stderr) + ))) } } @@ -160,32 +151,29 @@ impl DockerCompose { let output = self.run_compose(&["port", service, &container_port.to_string()])?; if !output.status.success() { - return Err(io::Error::new( - io::ErrorKind::Other, - format!( - "docker compose port failed for file '{}' and project '{}', service '{}' and port '{}': stderr: {} stdout: {}", - self.file.display(), - self.project, - service, - container_port, - String::from_utf8_lossy(&output.stderr), - String::from_utf8_lossy(&output.stdout) - ), - )); + return Err(io::Error::other(format!( + "docker compose port failed for file '{}' and project '{}', service '{}' and port '{}': stderr: {} stdout: {}", + self.file.display(), + self.project, + service, + container_port, + String::from_utf8_lossy(&output.stderr), + String::from_utf8_lossy(&output.stdout) + ))); } let stdout = String::from_utf8_lossy(&output.stdout); let first_line = stdout .lines() .next() - .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "docker compose port returned no output"))?; + .ok_or_else(|| io::Error::other("docker compose port returned no output"))?; let host_port = first_line .rsplit(':') .next() - .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "docker compose port output has no ':' separator"))? + .ok_or_else(|| io::Error::other("docker compose port output has no ':' separator"))? .parse::() - .map_err(|_| io::Error::new(io::ErrorKind::Other, format!("invalid host port in output: '{first_line}'")))?; + .map_err(|_| io::Error::other(format!("invalid host port in output: '{first_line}'")))?; Ok(host_port) } @@ -216,12 +204,9 @@ impl DockerCompose { .logs(&[service]) .unwrap_or_else(|error| format!("failed to collect compose logs output: {error}")); - return Err(io::Error::new( - io::ErrorKind::Other, - format!( - "compose service '{service}' exited while waiting for port mapping '{container_port}'.\nCompose ps:\n{ps_output}\nCompose logs:\n{logs_output}" - ), - )); + return Err(io::Error::other(format!( + "compose service '{service}' exited while waiting for port mapping '{container_port}'.\nCompose ps:\n{ps_output}\nCompose logs:\n{logs_output}" + ))); } } @@ -284,15 +269,12 @@ impl DockerCompose { if output.status.success() { Ok(String::from_utf8_lossy(&output.stdout).to_string()) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!( - "docker compose ps failed for file '{}' and project '{}': {}", - self.file.display(), - self.project, - String::from_utf8_lossy(&output.stderr) - ), - )) + Err(io::Error::other(format!( + "docker compose ps failed for file '{}' and project '{}': {}", + self.file.display(), + self.project, + String::from_utf8_lossy(&output.stderr) + ))) } } @@ -310,15 +292,12 @@ impl DockerCompose { if output.status.success() { Ok(String::from_utf8_lossy(&output.stdout).to_string()) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!( - "docker compose logs failed for file '{}' and project '{}': {}", - self.file.display(), - self.project, - String::from_utf8_lossy(&output.stderr) - ), - )) + Err(io::Error::other(format!( + "docker compose logs failed for file '{}' and project '{}': {}", + self.file.display(), + self.project, + String::from_utf8_lossy(&output.stderr) + ))) } } diff --git a/src/console/ci/e2e/docker.rs b/src/console/ci/e2e/docker.rs index 89d258d2c..89ea4bbce 100644 --- a/src/console/ci/e2e/docker.rs +++ b/src/console/ci/e2e/docker.rs @@ -45,10 +45,9 @@ impl Docker { if status.success() { Ok(()) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!("Failed to build Docker image from dockerfile {dockerfile}"), - )) + Err(io::Error::other(format!( + "Failed to build Docker image from dockerfile {dockerfile}" + ))) } } @@ -98,10 +97,7 @@ impl Docker { output, }) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!("Failed to run Docker image {image}"), - )) + Err(io::Error::other(format!("Failed to run Docker image {image}"))) } } @@ -116,10 +112,10 @@ impl Docker { if status.success() { Ok(()) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!("Failed to stop Docker container {}", container.name), - )) + Err(io::Error::other(format!( + "Failed to stop Docker container {}", + container.name + ))) } } @@ -134,10 +130,7 @@ impl Docker { if status.success() { Ok(()) } else { - Err(io::Error::new( - io::ErrorKind::Other, - format!("Failed to remove Docker container {container}"), - )) + Err(io::Error::other(format!("Failed to remove Docker container {container}"))) } } @@ -152,10 +145,9 @@ impl Docker { 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}"), - )) + Err(io::Error::other(format!( + "Failed to fetch logs from Docker container {container}" + ))) } } diff --git a/src/console/ci/e2e/tracker_checker.rs b/src/console/ci/e2e/tracker_checker.rs index a39e68c93..13f27fd7d 100644 --- a/src/console/ci/e2e/tracker_checker.rs +++ b/src/console/ci/e2e/tracker_checker.rs @@ -20,6 +20,6 @@ pub fn run(config_content: &str) -> io::Result<()> { if status.success() { Ok(()) } else { - Err(io::Error::new(io::ErrorKind::Other, "Failed to run Tracker Checker")) + Err(io::Error::other("Failed to run Tracker Checker")) } } diff --git a/src/console/ci/e2e/tracker_container.rs b/src/console/ci/e2e/tracker_container.rs index 99760fd9b..92d546664 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::RngExt; +use rand::distr::Alphanumeric; use super::docker::{RunOptions, RunningContainer}; use super::logs_parser::RunningServices; diff --git a/src/console/ci/qbittorrent_e2e/qbittorrent/client.rs b/src/console/ci/qbittorrent_e2e/qbittorrent/client.rs index 1351b7795..962949f1b 100644 --- a/src/console/ci/qbittorrent_e2e/qbittorrent/client.rs +++ b/src/console/ci/qbittorrent_e2e/qbittorrent/client.rs @@ -7,9 +7,9 @@ use reqwest::multipart::{Form, Part}; use tokio::sync::Mutex; use super::super::types::InfoHash; +use super::QBITTORRENT_WEBUI_PORT; use super::credentials::QbittorrentCredentials; use super::torrent::{TorrentInfo, TorrentProgress}; -use super::QBITTORRENT_WEBUI_PORT; const WEBUI_HEADER_HOST: &str = "localhost"; const WEBUI_HEADER_SCHEME: &str = "http"; diff --git a/src/console/ci/qbittorrent_e2e/qbittorrent/config_builder.rs b/src/console/ci/qbittorrent_e2e/qbittorrent/config_builder.rs index 8cac264cc..74b6fd8c0 100644 --- a/src/console/ci/qbittorrent_e2e/qbittorrent/config_builder.rs +++ b/src/console/ci/qbittorrent_e2e/qbittorrent/config_builder.rs @@ -3,8 +3,8 @@ use std::fs; use std::path::Path; use anyhow::Context; -use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use base64::Engine; +use base64::engine::general_purpose::STANDARD as BASE64_STANDARD; use pbkdf2::pbkdf2_hmac; use sha2::Sha512; diff --git a/src/console/ci/qbittorrent_e2e/services_setup.rs b/src/console/ci/qbittorrent_e2e/services_setup.rs index f52603f36..e5255a5cc 100644 --- a/src/console/ci/qbittorrent_e2e/services_setup.rs +++ b/src/console/ci/qbittorrent_e2e/services_setup.rs @@ -10,7 +10,7 @@ use std::time::Duration; use anyhow::Context; use super::client_role::ClientRole; -use super::qbittorrent::{QbittorrentClient, QBITTORRENT_WEBUI_PORT}; +use super::qbittorrent::{QBITTORRENT_WEBUI_PORT, QbittorrentClient}; use super::tracker::{TrackerApiClient, TrackerConfig}; use super::types::{ComposeProjectName, QbittorrentImage, TrackerImage}; use super::workspace::WorkspaceResources; diff --git a/src/console/ci/qbittorrent_e2e/types/compose_project_name.rs b/src/console/ci/qbittorrent_e2e/types/compose_project_name.rs index d556b658b..1831b94aa 100644 --- a/src/console/ci/qbittorrent_e2e/types/compose_project_name.rs +++ b/src/console/ci/qbittorrent_e2e/types/compose_project_name.rs @@ -1,8 +1,8 @@ use std::fmt; use std::ops::Deref; -use rand::distr::Alphanumeric; use rand::RngExt; +use rand::distr::Alphanumeric; /// A Docker Compose project name generated for one E2E test run. /// diff --git a/tests/servers/api/contract/stats/mod.rs b/tests/servers/api/contract/stats/mod.rs index d50bc58a5..e2cbb424d 100644 --- a/tests/servers/api/contract/stats/mod.rs +++ b/tests/servers/api/contract/stats/mod.rs @@ -2,8 +2,8 @@ use std::env; use std::str::FromStr as _; 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 bittorrent_tracker_client::http::client::requests::announce::QueryBuilder; use reqwest::Url; use serde::Deserialize; use tokio::time::Duration; @@ -49,7 +49,14 @@ async fn the_stats_api_endpoint_should_return_the_global_stats() { admin = "MyAccessToken" "#; - env::set_var("TORRUST_TRACKER_CONFIG_TOML", config_with_two_http_trackers); + // SAFETY: `std::env::set_var` is unsafe in Rust 2024 because concurrent reads from + // other threads in the same process are undefined behaviour. This test is the only + // function in this integration binary that writes `TORRUST_TRACKER_CONFIG_TOML`, and + // each test in this file binds to unique fixed ports, making parallel execution + // impossible (port conflicts). In practice the tests therefore run serially, but the + // safety guarantee is not formally enforced by the test runner. For strict soundness, + // run the integration suite with `RUST_TEST_THREADS=1`. + unsafe { env::set_var("TORRUST_TRACKER_CONFIG_TOML", config_with_two_http_trackers) }; let (_app_container, _jobs) = app::run().await;