fx_torrent/tracker/
connection.rs1use 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
9pub type ConnectionFactory = dyn Fn() -> Connection + Send + Sync;
11
12#[derive(Debug)]
14pub enum Connection {
15 Http(HttpClient),
16 Udp(UdpConnection),
17 Other(Box<dyn Extension>),
18}
19
20impl Connection {
21 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 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 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 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#[async_trait]
93pub trait Extension: Debug + Send + Sync {
94 async fn announce(&self, announcement: Announcement) -> Result<AnnouncementResponse>;
106
107 async fn scrape(&self, hashes: &[InfoHash]) -> Result<ScrapeResult>;
117
118 fn metrics(&self) -> &ConnectionMetrics;
120
121 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 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 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}