Skip to content

Commit

Permalink
dev: use shared client requests and responses for testing
Browse files Browse the repository at this point in the history
  • Loading branch information
da2ce7 committed Mar 29, 2024
1 parent d67bae0 commit 93b8b2a
Show file tree
Hide file tree
Showing 22 changed files with 311 additions and 1,071 deletions.
7 changes: 6 additions & 1 deletion packages/primitives/src/announce_event.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,24 @@
//!
//! Distributed under Apache 2.0 license
use derive_more::Display;
use serde::{Deserialize, Serialize};

/// Announce events. Described on the
/// [BEP 3. The `BitTorrent` Protocol Specification](https://www.bittorrent.org/beps/bep_0003.html)
#[derive(Hash, Clone, Copy, Debug, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
#[derive(Hash, Clone, Copy, Debug, Display, Serialize, Deserialize, PartialEq, Eq, PartialOrd, Ord)]
pub enum AnnounceEvent {
/// The peer has started downloading the torrent.
#[display(fmt = "started")]
Started,
/// The peer has ceased downloading the torrent.
#[display(fmt = "stopped")]
Stopped,
/// The peer has completed downloading the torrent.
#[display(fmt = "completed")]
Completed,
/// This is one of the announcements done at regular intervals.
#[display(fmt = "")]
None,
}

Expand Down
4 changes: 2 additions & 2 deletions packages/primitives/src/info_hash.rs
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,8 @@ impl std::convert::From<&DefaultHasher> for InfoHash {
}
}

impl std::convert::From<&i32> for InfoHash {
fn from(n: &i32) -> InfoHash {
impl std::convert::From<i32> for InfoHash {
fn from(n: i32) -> InfoHash {
let n = n.to_le_bytes();
InfoHash([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, n[0], n[1], n[2], n[3]])
}
Expand Down
7 changes: 4 additions & 3 deletions packages/primitives/src/peer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -392,13 +392,14 @@ pub mod fixture {

#[allow(dead_code)]
#[must_use]
pub fn build(self) -> Peer {
self.into()
pub fn with_event(mut self, event: AnnounceEvent) -> Self {
self.peer.event = event;
self
}

#[allow(dead_code)]
#[must_use]
pub fn into(self) -> Peer {
pub fn build(self) -> Peer {
self.peer
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/torrent-repository/tests/repository/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ fn many_out_of_order() -> Entries {
let mut entry = EntrySingle::default();
entry.insert_or_update_peer(&a_started_peer(i));

entries.insert((InfoHash::from(&i), entry));
entries.insert((InfoHash::from(i), entry));
}

// we keep the random order from the hashed set for the vector.
Expand Down
7 changes: 2 additions & 5 deletions src/console/clients/http/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use std::time::Duration;

use thiserror::Error;
use torrust_tracker_primitives::info_hash::InfoHash;
use torrust_tracker_primitives::peer;
use url::Url;

use crate::shared::bit_torrent::tracker::http::client::requests::{announce, scrape};
Expand Down Expand Up @@ -35,11 +36,7 @@ pub async fn check_http_announce(url: &Url, timeout: Duration, info_hash: InfoHa
let client = Client::new(url.clone(), timeout).map_err(|err| Error::HttpClientError { err })?;

let response = client
.announce(
&announce::QueryBuilder::with_default_values()
.with_info_hash(&info_hash)
.build(),
)
.announce(&announce::QueryBuilder::new(info_hash, peer::Id::from(1), 17548).build())
.await
.map_err(|err| Error::HttpClientError { err })?;

Expand Down
87 changes: 31 additions & 56 deletions src/shared/bit_torrent/tracker/http/client/requests/announce.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
use std::fmt;
use std::net::{IpAddr, Ipv4Addr};
use std::str::FromStr;
use std::net::IpAddr;

use serde_repr::Serialize_repr;
use torrust_tracker_primitives::announce_event::AnnounceEvent;
use torrust_tracker_primitives::info_hash::InfoHash;
use torrust_tracker_primitives::peer;

Expand All @@ -12,13 +12,13 @@ use crate::shared::bit_torrent::tracker::http::{percent_encode_byte_array, ByteA
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub(super) struct Query {
pub info_hash: ByteArray20,
pub peer_addr: IpAddr,
pub downloaded: BaseTenASCII,
pub uploaded: BaseTenASCII,
pub peer_addr: Option<IpAddr>,
pub downloaded: Option<BaseTenASCII>,
pub uploaded: Option<BaseTenASCII>,
pub peer_id: ByteArray20,
pub port: PortNumber,
pub left: BaseTenASCII,
pub event: Option<Event>,
pub left: Option<BaseTenASCII>,
pub event: Option<AnnounceEvent>,
pub compact: Option<Compact>,
}

Expand All @@ -31,23 +31,6 @@ impl fmt::Display for Query {
pub type BaseTenASCII = u64;
pub type PortNumber = u16;

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
pub enum Event {
//Started,
//Stopped,
Completed,
}

impl fmt::Display for Event {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
//Event::Started => write!(f, "started"),
//Event::Stopped => write!(f, "stopped"),
Event::Completed => write!(f, "completed"),
}
}
}

#[derive(Serialize_repr, PartialEq, Eq, Debug, Clone, Copy)]
#[repr(u8)]
pub enum Compact {
Expand All @@ -64,6 +47,7 @@ impl fmt::Display for Compact {
}
}

#[derive(Debug)]
pub struct QueryBuilder {
query: Query,
}
Expand All @@ -73,49 +57,43 @@ impl QueryBuilder {
///
/// Will panic if the default info-hash value is not a valid info-hash.
#[must_use]
pub fn with_default_values() -> QueryBuilder {
pub fn new(info_hash: InfoHash, peer_id: peer::Id, port: u16) -> QueryBuilder {
Self {
query: Query {
info_hash: InfoHash::from_str("9c38422213e30bff212b30c360d26f9a02136422").unwrap().0, // # DevSkim: ignore DS173237
peer_addr: IpAddr::V4(Ipv4Addr::new(192, 168, 1, 88)),
downloaded: 0,
uploaded: 0,
peer_id: peer::Id(*b"-qB00000000000000001").0,
port: 17548,
left: 0,
event: Some(Event::Completed),
compact: Some(Compact::NotAccepted),
info_hash: info_hash.0,
peer_addr: None,
downloaded: None,
uploaded: None,
peer_id: peer_id.0,
port,
left: None,
event: None,
compact: None,
},
}
}

#[must_use]
pub fn with_info_hash(mut self, info_hash: &InfoHash) -> Self {
self.query.info_hash = info_hash.0;
pub fn with_event(mut self, event: AnnounceEvent) -> Self {
self.query.event = Some(event);
self
}

#[must_use]
pub fn with_peer_id(mut self, peer_id: &peer::Id) -> Self {
self.query.peer_id = peer_id.0;
pub fn with_compact(mut self) -> Self {
self.query.compact = Some(Compact::Accepted);
self
}

#[must_use]
pub fn with_compact(mut self, compact: Compact) -> Self {
self.query.compact = Some(compact);
pub fn without_compact(mut self) -> Self {
self.query.compact = Some(Compact::NotAccepted);
self
}

#[must_use]
pub fn with_peer_addr(mut self, peer_addr: &IpAddr) -> Self {
self.query.peer_addr = *peer_addr;
self
}

#[must_use]
pub fn without_compact(mut self) -> Self {
self.query.compact = None;
self.query.peer_addr = Some(*peer_addr);
self
}

Expand Down Expand Up @@ -212,19 +190,16 @@ impl From<&Query> for QueryParams {
fn from(value: &Query) -> Self {
let query = value;

let event = query.event.as_ref().map(std::string::ToString::to_string);
let compact = query.compact.as_ref().map(std::string::ToString::to_string);

Self {
info_hash: Some(percent_encode_byte_array(&query.info_hash)),
peer_addr: Some(query.peer_addr.to_string()),
downloaded: Some(query.downloaded.to_string()),
uploaded: Some(query.uploaded.to_string()),
peer_addr: query.peer_addr.as_ref().map(std::string::ToString::to_string),
downloaded: query.downloaded.as_ref().map(std::string::ToString::to_string),
uploaded: query.uploaded.as_ref().map(std::string::ToString::to_string),
peer_id: Some(percent_encode_byte_array(&query.peer_id)),
port: Some(query.port.to_string()),
left: Some(query.left.to_string()),
event,
compact,
left: query.left.as_ref().map(std::string::ToString::to_string),
event: query.event.as_ref().map(std::string::ToString::to_string),
compact: query.compact.as_ref().map(std::string::ToString::to_string),
}
}
}
Expand Down
22 changes: 13 additions & 9 deletions src/shared/bit_torrent/tracker/http/client/requests/scrape.rs
Original file line number Diff line number Diff line change
Expand Up @@ -90,33 +90,37 @@ impl Query {

#[derive(Default)]
pub struct QueryBuilder {
scrape_query: Query,
query: Query,
}

impl FromIterator<InfoHash> for QueryBuilder {
fn from_iter<T: IntoIterator<Item = InfoHash>>(iter: T) -> Self {
Self {
scrape_query: Query::from_iter(iter),
query: Query::from_iter(iter),
}
}
}

impl QueryBuilder {
#[must_use]
pub fn with_one_info_hash(mut self, info_hash: &InfoHash) -> Self {
self.scrape_query.infohashes = [info_hash.0].to_vec();
self
impl From<&InfoHash> for QueryBuilder {
fn from(value: &InfoHash) -> Self {
Self {
query: Query {
infohashes: [value.0].to_vec(),
},
}
}
}

impl QueryBuilder {
#[must_use]
pub fn add_info_hash(mut self, info_hash: &InfoHash) -> Self {
self.scrape_query.infohashes.push(info_hash.0);
self.query.infohashes.push(info_hash.0);
self
}

#[must_use]
pub fn build(self) -> Scrape {
self.scrape_query.into()
self.query.into()
}
}

Expand Down
26 changes: 25 additions & 1 deletion src/shared/bit_torrent/tracker/http/client/responses/announce.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,35 @@ pub(super) struct Response {
pub peers: Vec<DictionaryPeer>, // Peers using IPV4 and IPV6
}

#[derive(Default)]
pub struct ResponseBuilder {
response: Response,
}

impl ResponseBuilder {
#[must_use]
pub fn new(policy: &torrust_tracker_configuration::AnnouncePolicy) -> Self {
Self {
response: Response {
interval: policy.interval,
min_interval: policy.interval_min,
..Default::default()
},
}
}

#[must_use]
pub fn with_complete(mut self, complete: u32) -> Self {
self.response.complete = complete;
self
}

#[must_use]
pub fn with_peers(mut self, peers: Vec<DictionaryPeer>) -> Self {
self.response.peers = peers;
self
}
}

impl TryFrom<&Bytes> for ResponseBuilder {
type Error = BencodeParseError;

Expand Down
8 changes: 5 additions & 3 deletions src/shared/bit_torrent/tracker/http/client/responses/mod.rs
Original file line number Diff line number Diff line change
@@ -1,20 +1,22 @@
use std::sync::Arc;

use derive_more::From;
use serde::Serialize;
use serde::{Deserialize, Serialize};
use thiserror::Error;

pub mod announce;
pub mod error;
pub mod scrape;

#[derive(Serialize, Debug, From, PartialEq, Eq, Clone)]
#[derive(Serialize, Deserialize, Debug, From, PartialEq, Eq, Clone)]
pub struct Announce {
#[serde(flatten)]
response: announce::Response,
}

#[derive(Serialize, Debug, From, PartialEq, Eq, Clone)]
#[derive(Serialize, Deserialize, Debug, From, PartialEq, Eq, Clone)]
pub struct Scrape {
#[serde(flatten)]
response: scrape::Response,
}

Expand Down
2 changes: 1 addition & 1 deletion tests/servers/api/v1/contract/context/stats.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ async fn should_allow_getting_tracker_statistics() {

env.add_torrent_peer(
&InfoHash::from_str("9e0217d0fa71c87332cd8bf9dbeabcb2c2cf3c4d").unwrap(),
&PeerBuilder::default().into(),
&PeerBuilder::default().build(),
)
.await;

Expand Down
Loading

0 comments on commit 93b8b2a

Please sign in to comment.