Skip to main content

fx_torrent/tracker/
connection.rs

1use crate::tracker::{
2    Announcement, AnnouncementResponse, ConnectionMetrics, HttpClient, Result, ScrapeResult,
3    UdpConnection,
4};
5use crate::InfoHash;
6use async_trait::async_trait;
7use std::fmt::Debug;
8
9/// Factory for creating tracker connections.
10pub type ConnectionFactory = dyn Fn() -> Connection + Send + Sync;
11
12/// The underlying connection of a tracker.
13#[derive(Debug)]
14pub enum Connection {
15    Http(HttpClient),
16    Udp(UdpConnection),
17    Other(Box<dyn Extension>),
18}
19
20impl Connection {
21    /// Returns the announcement response for the torrent hash from the tracker.
22    /// This will send the known peer info to the tracker with the type of announcement.
23    ///
24    /// # Arguments
25    ///
26    /// * `info_hash` - The `InfoHash` of the torrent to announce.
27    /// * `event` - The announcement event type to announce.
28    pub async fn announce(&self, announcement: Announcement) -> Result<AnnouncementResponse> {
29        match self {
30            Connection::Http(http) => http.announce(announcement).await,
31            Connection::Udp(udp) => udp.announce(announcement).await,
32            Connection::Other(other) => other.announce(announcement).await,
33        }
34    }
35
36    /// Returns the scrape result for one or more info hashes from the tracker.
37    ///
38    /// # Arguments
39    ///
40    /// * `hashes` - The info hashes to retrieve the metrics from.
41    pub async fn scrape(&self, hashes: &[InfoHash]) -> Result<ScrapeResult> {
42        match self {
43            Connection::Http(http) => http.scrape(hashes).await,
44            Connection::Udp(udp) => udp.scrape(hashes).await,
45            Connection::Other(other) => other.scrape(hashes).await,
46        }
47    }
48
49    /// Returns the connection metrics.
50    pub fn metrics(&self) -> &ConnectionMetrics {
51        match self {
52            Connection::Http(http) => http.metrics(),
53            Connection::Udp(udp) => udp.metrics(),
54            Connection::Other(other) => other.metrics(),
55        }
56    }
57
58    /// Close the tracker connection and cancel any pending tasks.
59    ///
60    /// This method should gracefully shut down the connection to the tracker and cancel any ongoing operations.
61    pub async fn close(&self) {
62        match self {
63            Connection::Http(http) => http.close(),
64            Connection::Udp(udp) => udp.close(),
65            Connection::Other(other) => other.close().await,
66        }
67    }
68}
69
70impl From<HttpClient> for Connection {
71    fn from(value: HttpClient) -> Self {
72        Self::Http(value)
73    }
74}
75
76impl From<UdpConnection> for Connection {
77    fn from(value: UdpConnection) -> Self {
78        Self::Udp(value)
79    }
80}
81
82impl<E> From<E> for Connection
83where
84    E: Extension + 'static,
85{
86    fn from(value: E) -> Self {
87        Self::Other(Box::new(value))
88    }
89}
90
91/// Extension trait for tracker connections.
92#[async_trait]
93pub trait Extension: Debug + Send + Sync {
94    /// Announce the given torrent hash to the tracker.
95    /// This will send the known peer info to the tracker with the type of announcement.
96    ///
97    /// # Arguments
98    ///
99    /// * `info_hash` - The `InfoHash` of the torrent to announce.
100    /// * `event` - The announcement event type to announce.
101    ///
102    /// # Returns
103    ///
104    /// Returns the tracker announcement response for the given announcement.
105    async fn announce(&self, announcement: Announcement) -> Result<AnnouncementResponse>;
106
107    /// Scrape the tracker for metrics for one or more info hashes.
108    ///
109    /// # Arguments
110    ///
111    /// * `hashes` - The info hashes to retrieve the metrics from.
112    ///
113    /// # Returns
114    ///
115    /// Returns the scrape result from the tracker for the given hashes.
116    async fn scrape(&self, hashes: &[InfoHash]) -> Result<ScrapeResult>;
117
118    /// Returns the connection metrics.
119    fn metrics(&self) -> &ConnectionMetrics;
120
121    /// Close the tracker connection and cancel any pending tasks.
122    ///
123    /// This method should gracefully shut down the connection to the tracker and cancel any ongoing operations.
124    async fn close(&self);
125}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    mod extension {
132        use super::*;
133        use crate::peer::PeerId;
134        use crate::tracker::AnnounceEvent;
135        use mockall::mock;
136        use std::str::FromStr;
137        use tokio::sync::oneshot;
138
139        mock! {
140            #[derive(Debug)]
141            pub Extension {}
142
143            #[async_trait]
144            impl Extension for Extension {
145                async fn announce(&self, announcement: Announcement) -> Result<AnnouncementResponse>;
146                async fn scrape(&self, hashes: &[InfoHash]) -> Result<ScrapeResult>;
147                fn metrics(&self) -> &ConnectionMetrics;
148                async fn close(&self);
149            }
150        }
151
152        #[tokio::test]
153        async fn test_announce() {
154            let info_hash = InfoHash::from_str("A1DFEFEC1A9DD7FA8A041EBEEEA271DB55126D2F").unwrap();
155            let (tx, rx) = oneshot::channel();
156            let mut extension = MockExtension::default();
157            extension
158                .expect_announce()
159                .times(1)
160                .return_once(|announcement: Announcement| {
161                    let _ = tx.send(announcement);
162                    Ok(AnnouncementResponse {
163                        interval_seconds: 120,
164                        external_ip: None,
165                        leechers: 12,
166                        seeders: 43,
167                        peers: vec![],
168                    })
169                });
170            let expected_announcement = Announcement {
171                info_hash,
172                peer_id: PeerId::new(),
173                peer_port: 6881,
174                event: AnnounceEvent::Started,
175                bytes_completed: 0,
176                bytes_remaining: 0,
177            };
178            let connection: Connection = extension.into();
179
180            // sent the announcement to the connection
181            let result = connection
182                .announce(expected_announcement.clone())
183                .await
184                .expect("expected the announce to succeed");
185            assert_eq!(result.interval_seconds, 120);
186            assert_eq!(result.leechers, 12);
187            assert_eq!(result.seeders, 43);
188
189            // verify the received announcement in the extension
190            let announcement = timeout!(Duration::from_millis(100), rx).unwrap();
191            assert_eq!(
192                expected_announcement, announcement,
193                "expected the announcement to match"
194            );
195        }
196
197        #[test]
198        fn test_metrics() {
199            let mut extension = MockExtension::default();
200            extension.expect_metrics().times(1).return_const({
201                let metrics = ConnectionMetrics::default();
202                metrics.bytes_in.inc_by(64);
203                metrics
204            });
205            let connection: Connection = extension.into();
206
207            let result = connection.metrics();
208            assert_eq!(result.bytes_in.get(), 64);
209        }
210
211        #[tokio::test]
212        async fn test_close() {
213            let mut extension = MockExtension::default();
214            extension.expect_close().times(1).return_const(());
215            let connection: Connection = extension.into();
216
217            connection.close().await;
218        }
219    }
220}