Skip to content

Commit 0e6fe33

Browse files
committed
dev: Announce Responce Cleanup
1 parent 58a57d3 commit 0e6fe33

File tree

20 files changed

+396
-471
lines changed

20 files changed

+396
-471
lines changed

Cargo.lock

+1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

+8-1
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,14 @@ serde_urlencoded = "0"
7979
torrust-tracker-test-helpers = { version = "3.0.0-alpha.12-develop", path = "packages/test-helpers" }
8080

8181
[workspace]
82-
members = ["contrib/bencode", "packages/configuration", "packages/located-error", "packages/primitives", "packages/test-helpers", "packages/torrent-repository-benchmarks"]
82+
members = [
83+
"contrib/bencode",
84+
"packages/configuration",
85+
"packages/located-error",
86+
"packages/primitives",
87+
"packages/test-helpers",
88+
"packages/torrent-repository-benchmarks",
89+
]
8390

8491
[profile.dev]
8592
debug = 1

cSpell.json

+1
Original file line numberDiff line numberDiff line change
@@ -50,6 +50,7 @@
5050
"Hydranode",
5151
"Icelake",
5252
"imdl",
53+
"impls",
5354
"incompletei",
5455
"infohash",
5556
"infohashes",

packages/configuration/Cargo.toml

+1
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ version.workspace = true
1616

1717
[dependencies]
1818
config = "0"
19+
derive_more = "0"
1920
log = { version = "0", features = ["release_max_level_info"] }
2021
serde = { version = "1", features = ["derive"] }
2122
serde_with = "3"

packages/configuration/src/lib.rs

+3-1
Original file line numberDiff line numberDiff line change
@@ -236,6 +236,7 @@ use std::sync::Arc;
236236
use std::{env, fs};
237237

238238
use config::{Config, ConfigError, File, FileFormat};
239+
use derive_more::Constructor;
239240
use serde::{Deserialize, Serialize};
240241
use serde_with::{serde_as, NoneAsEmptyString};
241242
use thiserror::Error;
@@ -388,7 +389,7 @@ pub struct HealthCheckApi {
388389
}
389390

390391
/// Announce policy
391-
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
392+
#[derive(PartialEq, Eq, Debug, Clone, Copy, Constructor)]
392393
pub struct AnnouncePolicy {
393394
/// Interval in seconds that the client should wait between sending regular
394395
/// announce requests to the tracker.
@@ -537,6 +538,7 @@ impl From<ConfigError> for Error {
537538
impl Default for Configuration {
538539
fn default() -> Self {
539540
let announce_policy = AnnouncePolicy::default();
541+
540542
let mut configuration = Configuration {
541543
log_level: Option::from(String::from("info")),
542544
mode: TrackerMode::Public,

src/core/databases/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -134,7 +134,7 @@ pub trait Database: Sync + Send {
134134
/// # Errors
135135
///
136136
/// Will return `Err` if unable to save.
137-
async fn save_persistent_torrent(&self, info_hash: &InfoHash, completed: u32) -> Result<(), Error>;
137+
async fn save_persistent_torrent(&self, info_hash: &InfoHash, downloaded: u32) -> Result<(), Error>;
138138

139139
// Whitelist
140140

src/core/mod.rs

+15-19
Original file line numberDiff line numberDiff line change
@@ -98,12 +98,12 @@
9898
//!
9999
//! ```rust,no_run
100100
//! use torrust_tracker::core::peer::Peer;
101+
//! use torrust_tracker_configuration::AnnouncePolicy;
101102
//!
102103
//! pub struct AnnounceData {
103104
//! pub peers: Vec<Peer>,
104105
//! pub swarm_stats: SwarmStats,
105-
//! pub interval: u32, // Option `announce_interval` from core tracker configuration
106-
//! pub interval_min: u32, // Option `min_announce_interval` from core tracker configuration
106+
//! pub policy: AnnouncePolicy, // the tracker announce policy.
107107
//! }
108108
//!
109109
//! pub struct SwarmStats {
@@ -445,9 +445,10 @@ use std::panic::Location;
445445
use std::sync::Arc;
446446
use std::time::Duration;
447447

448+
use derive_more::Constructor;
448449
use futures::future::join_all;
449450
use tokio::sync::mpsc::error::SendError;
450-
use torrust_tracker_configuration::Configuration;
451+
use torrust_tracker_configuration::{AnnouncePolicy, Configuration};
451452
use torrust_tracker_primitives::TrackerMode;
452453

453454
use self::auth::Key;
@@ -487,7 +488,7 @@ pub struct Tracker {
487488
/// Structure that holds general `Tracker` torrents metrics.
488489
///
489490
/// Metrics are aggregate values for all torrents.
490-
#[derive(Debug, PartialEq, Default)]
491+
#[derive(Copy, Clone, Debug, PartialEq, Default)]
491492
pub struct TorrentsMetrics {
492493
/// Total number of seeders for all torrents
493494
pub seeders: u64,
@@ -500,20 +501,14 @@ pub struct TorrentsMetrics {
500501
}
501502

502503
/// Structure that holds the data returned by the `announce` request.
503-
#[derive(Debug, PartialEq, Default)]
504+
#[derive(Clone, Debug, PartialEq, Constructor, Default)]
504505
pub struct AnnounceData {
505506
/// The list of peers that are downloading the same torrent.
506507
/// It excludes the peer that made the request.
507508
pub peers: Vec<Peer>,
508509
/// Swarm statistics
509-
pub swarm_stats: SwarmStats,
510-
/// The interval in seconds that the client should wait between sending
511-
/// regular requests to the tracker.
512-
/// Refer to [`announce_interval`](torrust_tracker_configuration::Configuration::announce_interval).
513-
pub interval: u32,
514-
/// The minimum announce interval in seconds that the client should wait.
515-
/// Refer to [`min_announce_interval`](torrust_tracker_configuration::Configuration::min_announce_interval).
516-
pub interval_min: u32,
510+
pub stats: SwarmStats,
511+
pub policy: AnnouncePolicy,
517512
}
518513

519514
/// Structure that holds the data returned by the `scrape` request.
@@ -628,11 +623,12 @@ impl Tracker {
628623

629624
let peers = self.get_torrent_peers_for_peer(info_hash, peer).await;
630625

626+
let policy = AnnouncePolicy::new(self.config.announce_interval, self.config.min_announce_interval);
627+
631628
AnnounceData {
632629
peers,
633-
swarm_stats,
634-
interval: self.config.announce_interval,
635-
interval_min: self.config.min_announce_interval,
630+
stats: swarm_stats,
631+
policy,
636632
}
637633
}
638634

@@ -1390,7 +1386,7 @@ mod tests {
13901386

13911387
let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await;
13921388

1393-
assert_eq!(announce_data.swarm_stats.complete, 1);
1389+
assert_eq!(announce_data.stats.complete, 1);
13941390
}
13951391

13961392
#[tokio::test]
@@ -1401,7 +1397,7 @@ mod tests {
14011397

14021398
let announce_data = tracker.announce(&sample_info_hash(), &mut peer, &peer_ip()).await;
14031399

1404-
assert_eq!(announce_data.swarm_stats.incomplete, 1);
1400+
assert_eq!(announce_data.stats.incomplete, 1);
14051401
}
14061402

14071403
#[tokio::test]
@@ -1415,7 +1411,7 @@ mod tests {
14151411
let mut completed_peer = completed_peer();
14161412
let announce_data = tracker.announce(&sample_info_hash(), &mut completed_peer, &peer_ip()).await;
14171413

1418-
assert_eq!(announce_data.swarm_stats.downloaded, 1);
1414+
assert_eq!(announce_data.stats.downloaded, 1);
14191415
}
14201416
}
14211417
}

src/core/peer.rs

+78-2
Original file line numberDiff line numberDiff line change
@@ -277,9 +277,85 @@ impl Serialize for Id {
277277
}
278278
}
279279

280-
#[cfg(test)]
281-
mod test {
280+
pub mod fixture {
281+
use std::net::SocketAddr;
282+
283+
use aquatic_udp_protocol::NumberOfBytes;
284+
285+
use super::{Id, Peer};
286+
287+
#[derive(PartialEq, Debug)]
288+
289+
pub struct PeerBuilder {
290+
peer: Peer,
291+
}
292+
293+
#[allow(clippy::derivable_impls)]
294+
impl Default for PeerBuilder {
295+
fn default() -> Self {
296+
Self { peer: Peer::default() }
297+
}
298+
}
299+
300+
impl PeerBuilder {
301+
#[allow(dead_code)]
302+
#[must_use]
303+
pub fn with_peer_id(mut self, peer_id: &Id) -> Self {
304+
self.peer.peer_id = *peer_id;
305+
self
306+
}
307+
308+
#[allow(dead_code)]
309+
#[must_use]
310+
pub fn with_peer_addr(mut self, peer_addr: &SocketAddr) -> Self {
311+
self.peer.peer_addr = *peer_addr;
312+
self
313+
}
314+
315+
#[allow(dead_code)]
316+
#[must_use]
317+
pub fn with_bytes_pending_to_download(mut self, left: i64) -> Self {
318+
self.peer.left = NumberOfBytes(left);
319+
self
320+
}
282321

322+
#[allow(dead_code)]
323+
#[must_use]
324+
pub fn with_no_bytes_pending_to_download(mut self) -> Self {
325+
self.peer.left = NumberOfBytes(0);
326+
self
327+
}
328+
329+
#[allow(dead_code)]
330+
#[must_use]
331+
pub fn build(self) -> Peer {
332+
self.into()
333+
}
334+
335+
#[allow(dead_code)]
336+
#[must_use]
337+
pub fn into(self) -> Peer {
338+
self.peer
339+
}
340+
}
341+
342+
impl Default for Peer {
343+
fn default() -> Self {
344+
Self {
345+
peer_id: Id(*b"-qB00000000000000000"),
346+
peer_addr: std::net::SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::new(126, 0, 0, 1)), 8080),
347+
updated: crate::shared::clock::DurationSinceUnixEpoch::new(1_669_397_478_934, 0),
348+
uploaded: NumberOfBytes(0),
349+
downloaded: NumberOfBytes(0),
350+
left: NumberOfBytes(0),
351+
event: aquatic_udp_protocol::AnnounceEvent::Started,
352+
}
353+
}
354+
}
355+
}
356+
357+
#[cfg(test)]
358+
pub mod test {
283359
mod torrent_peer_id {
284360
use crate::core::peer;
285361

src/core/torrent/mod.rs

+7-6
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ pub mod repository;
3333
use std::time::Duration;
3434

3535
use aquatic_udp_protocol::AnnounceEvent;
36+
use derive_more::Constructor;
3637
use serde::{Deserialize, Serialize};
3738

3839
use super::peer::{self, Peer};
@@ -56,13 +57,13 @@ pub struct Entry {
5657
/// Swarm metadata dictionary in the scrape response.
5758
///
5859
/// See [BEP 48: Tracker Protocol Extension: Scrape](https://www.bittorrent.org/beps/bep_0048.html)
59-
#[derive(Debug, PartialEq, Default)]
60+
#[derive(Copy, Clone, Debug, PartialEq, Default, Constructor)]
6061
pub struct SwarmMetadata {
61-
/// The number of peers that have ever completed downloading
62-
pub downloaded: u32,
63-
/// The number of active peers that have completed downloading (seeders)
64-
pub complete: u32,
65-
/// The number of active peers that have not completed downloading (leechers)
62+
/// (i.e `completed`): The number of peers that have ever completed downloading
63+
pub downloaded: u32, //
64+
/// (i.e `seeders`): The number of active peers that have completed downloading (seeders)
65+
pub complete: u32, //seeders
66+
/// (i.e `leechers`): The number of active peers that have not completed downloading (leechers)
6667
pub incomplete: u32,
6768
}
6869

src/servers/http/mod.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -152,7 +152,7 @@
152152
//! 000000f0: 65 e
153153
//! ```
154154
//!
155-
//! Refer to the [`Normal`](crate::servers::http::v1::responses::announce::Normal)
155+
//! Refer to the [`Normal`](crate::servers::http::v1::responses::announce::Normal), i.e. `Non-Compact`
156156
//! response for more information about the response.
157157
//!
158158
//! **Sample compact response**

src/servers/http/v1/handlers/announce.rs

+7-8
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@ use crate::servers::http::v1::extractors::authentication_key::Extract as Extract
2222
use crate::servers::http::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources;
2323
use crate::servers::http::v1::handlers::common::auth;
2424
use crate::servers::http::v1::requests::announce::{Announce, Compact, Event};
25-
use crate::servers::http::v1::responses::{self, announce};
25+
use crate::servers::http::v1::responses::{self};
2626
use crate::servers::http::v1::services::peer_ip_resolver::ClientIpSources;
2727
use crate::servers::http::v1::services::{self, peer_ip_resolver};
2828
use crate::shared::clock::{Current, Time};
@@ -117,13 +117,12 @@ async fn handle_announce(
117117
}
118118

119119
fn build_response(announce_request: &Announce, announce_data: AnnounceData) -> Response {
120-
match &announce_request.compact {
121-
Some(compact) => match compact {
122-
Compact::Accepted => announce::Compact::from(announce_data).into_response(),
123-
Compact::NotAccepted => announce::Normal::from(announce_data).into_response(),
124-
},
125-
// Default response format non compact
126-
None => announce::Normal::from(announce_data).into_response(),
120+
if announce_request.compact.as_ref().is_some_and(|f| *f == Compact::Accepted) {
121+
let response: responses::Announce<responses::Compact> = announce_data.into();
122+
response.into_response()
123+
} else {
124+
let response: responses::Announce<responses::Normal> = announce_data.into();
125+
response.into_response()
127126
}
128127
}
129128

src/servers/http/v1/requests/announce.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -180,7 +180,7 @@ impl fmt::Display for Event {
180180
/// Depending on the value of this param, the tracker will return a different
181181
/// response:
182182
///
183-
/// - [`Normal`](crate::servers::http::v1::responses::announce::Normal) response.
183+
/// - [`Normal`](crate::servers::http::v1::responses::announce::Normal), i.e. a `non-compact` response.
184184
/// - [`Compact`](crate::servers::http::v1::responses::announce::Compact) response.
185185
///
186186
/// Refer to [BEP 23. Tracker Returns Compact Peer Lists](https://www.bittorrent.org/beps/bep_0023.html)

0 commit comments

Comments
 (0)