fx-torrent 0.10.3

FX Torrent is a feature rich Bittorrent protocol implementation written in rust supporting Linux, MacOS and Windows.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
use crate::channel::{ChannelReceiver, ChannelSender, Reply};
use crate::metrics::Metric;
use crate::peer::PeerId;
use crate::tracker::{
    AnnounceEvent, Announcement, AnnouncementResponse, Result, ScrapeFileMetrics, ScrapeResult,
    Tracker, TrackerClientMetrics, TrackerError, TrackerHandle, TrackerState,
};
use crate::{InfoHash, Metrics};
use derive_more::Display;
use futures::future;
use fx_callback::{Callback, MultiThreadedCallback, Subscription};
use itertools::Itertools;
use log::{debug, info, trace, warn};
use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::io;
use std::net::SocketAddr;
use std::time::{Duration, Instant};
use tokio::task::JoinSet;
use tokio::{select, time};
use tokio_util::sync::CancellationToken;
use url::Url;

const DEFAULT_ANNOUNCEMENT_INTERVAL: Duration = Duration::from_secs(60);
const STATS_INTERVAL: Duration = Duration::from_secs(1);

/// Aggregated announcement result returned by one or more trackers.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct AnnouncementResult {
    /// The total number of leechers reported by the trackers.
    pub total_leechers: u64,
    /// The total number of seeders reported by the trackers.
    pub total_seeders: u64,
    /// The list of peers' addresses reported by the trackers.
    pub peers: Vec<SocketAddr>,
}

impl AnnouncementResult {
    /// Returns the total number of peers reported by the trackers.
    ///
    /// This is simply the length of [`Self::peers`].
    pub fn total_peers(&self) -> u64 {
        self.peers.len() as u64
    }
}

impl FromIterator<AnnouncementResult> for AnnouncementResult {
    fn from_iter<T: IntoIterator<Item = AnnouncementResult>>(iter: T) -> Self {
        let mut result = Self::default();
        for item in iter {
            result.total_leechers += item.total_leechers;
            result.total_seeders += item.total_seeders;
            result.peers.extend(item.peers);
        }
        result
    }
}

#[derive(Debug, Display, Clone, PartialEq)]
#[display("({}) {}", tier, url)]
pub struct TrackerEntry {
    /// The tier of the tracker.
    ///
    /// Lower values indicate higher priority.
    pub tier: u8,
    /// The tracker url to connect to.
    pub url: Url,
}

/// The event that can be emitted by the tracker client.
#[derive(Debug, Clone)]
pub enum TrackerClientEvent {
    /// Emitted when new peers have been discovered for a torrent.
    ///
    /// Contains the [`InfoHash`] of the torrent and the list of newly discovered peer addresses.
    PeersDiscovered(InfoHash, Vec<SocketAddr>),
    /// Emitted when a new tracker has been added to the client.
    ///
    /// Contains the handle of the added tracker.
    TrackerAdded(TrackerHandle),
    /// Emitted when the tracker client's metric stats are updated.
    ///
    /// This is emitted periodically based on [`STATS_INTERVAL`].
    Stats(TrackerClientMetrics),
}

impl PartialEq for TrackerClientEvent {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (
                TrackerClientEvent::PeersDiscovered(a, _),
                TrackerClientEvent::PeersDiscovered(b, _),
            ) => a == b,
            (TrackerClientEvent::TrackerAdded(a), TrackerClientEvent::TrackerAdded(b)) => a == b,
            (TrackerClientEvent::Stats(_), TrackerClientEvent::Stats(_)) => true,
            _ => false,
        }
    }
}

/// A tracker client that manages communication with one or more trackers
/// for a set of torrents.
///
/// It allows registering torrents, adding trackers, announcing events,
/// scraping statistics, and retrieving discovered peers.
#[derive(Debug, Display, Clone)]
#[display("{}", handle)]
pub struct TrackerClient {
    handle: TrackerHandle,
    sender: ChannelSender<TrackerClientCommand>,
    metrics: TrackerClientMetrics,
    callbacks: MultiThreadedCallback<TrackerClientEvent>,
    cancellation_token: CancellationToken,
}

impl TrackerClient {
    /// Creates a new instance for managing one or more client trackers.
    /// Clients scrape data from servers rather than collecting data received from clients.
    pub fn new(connection_timeout: Duration) -> Self {
        let (command_sender, command_receiver) = channel!(128);
        let mut inner = InnerClient::new(connection_timeout);
        let handle = inner.handle.clone();
        let metrics = inner.metrics.clone();
        let callbacks = inner.callbacks.clone();
        let cancellation_token = inner.cancellation_token.clone();

        // spawn the main loop in a separate task
        spawn!("TrackerClient::run", async move {
            inner.run(command_receiver).await;
        });

        Self {
            handle,
            sender: command_sender,
            metrics,
            callbacks,
            cancellation_token,
        }
    }

    /// Returns the aggregated metric stats of this tracker client.
    pub fn metrics(&self) -> &TrackerClientMetrics {
        &self.metrics
    }

    /// Returns the tracker for the given handle if found, else [None].
    pub async fn get(&self, handle: &TrackerHandle) -> Option<Tracker> {
        self.sender
            .send(|tx| TrackerClientCommand::GetTracker {
                handle: *handle,
                response: tx,
            })
            .await
            .await
            .ok()
            .flatten()
    }

    /// Returns the tracker for the given url if found, else [None].
    pub async fn get_by_url(&self, url: &Url) -> Option<Tracker> {
        self.sender
            .send(|tx| TrackerClientCommand::GetTrackerByUrl {
                url: url.clone(),
                response: tx,
            })
            .await
            .await
            .ok()
            .flatten()
    }

    /// Checks if a given tracker URL is known within this client.
    pub async fn is_tracker_url_known(&self, url: &Url) -> bool {
        self.sender
            .send(|tx| TrackerClientCommand::IsUrlKnown {
                url: url.clone(),
                response: tx,
            })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the URLs of all trackers managed by this client.
    ///
    /// This might return an empty list if no trackers have been added yet.
    pub async fn tracker_urls(&self) -> Vec<Url> {
        self.sender
            .send(|tx| TrackerClientCommand::GetTrackerUrls { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns all trackers managed by this client.
    ///
    /// This might return an empty list if no trackers have been added yet.
    pub async fn trackers(&self) -> Vec<Tracker> {
        self.sender
            .send(|tx| TrackerClientCommand::GetTrackers { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the number of trackers managed by this client.
    ///
    /// This might return `0` if no trackers have been added yet.
    pub async fn trackers_len(&self) -> usize {
        self.sender
            .send(|tx| TrackerClientCommand::GetTrackersLen { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns the number of torrents tracked by this client.
    ///
    /// This might return `0` if no torrents have been added yet.
    pub async fn torrents_len(&self) -> usize {
        self.sender
            .send(|tx| TrackerClientCommand::GetTorrentsLen { response: tx })
            .await
            .await
            .unwrap_or_default()
    }

    /// Registers a new torrent with the tracker client so that it can discover peers.
    ///
    /// If a torrent with the same [`InfoHash`] is already registered,
    /// this call is effectively a no-op.
    ///
    /// # Arguments
    ///
    /// * `peer_id` - The peer ID of the client.
    /// * `peer_port` - The port on which the client is listening.
    /// * `info_hash` - The info hash of the torrent.
    /// * `metrics` - The metrics of the torrent.
    pub async fn add_torrent(
        &self,
        peer_id: PeerId,
        peer_port: u16,
        info_hash: InfoHash,
        metrics: Metrics,
    ) -> Result<()> {
        self.sender
            .send(|tx| TrackerClientCommand::AddTorrent {
                peer_id,
                peer_port,
                info_hash,
                metrics,
                response: tx,
            })
            .await
            .await
    }

    /// Removes the given torrent [`InfoHash`] from the tracker client.
    /// This stops tracking the torrent and clears any discovered peers for it.
    ///
    /// # Arguments
    ///
    /// * `info_hash` - The info hash of the torrent.
    pub async fn remove_torrent(&self, info_hash: &InfoHash) {
        let _ = self
            .sender
            .fire_and_forget(TrackerClientCommand::RemoveTorrent {
                info_hash: info_hash.clone(),
            })
            .await;
    }

    /// Returns the discovered peers for the given info hash.
    ///
    /// The info hash should first be registered through [`TrackerClient::add_torrent`].
    pub async fn discovered_peers(&self, info_hash: &InfoHash) -> Option<Vec<SocketAddr>> {
        self.sender
            .send(|tx| TrackerClientCommand::DiscoveredTorrentPeers {
                info_hash: info_hash.clone(),
                response: tx,
            })
            .await
            .await
            .ok()
            .flatten()
            .map(|e| e.into_iter().collect_vec())
    }

    /// Adds a new tracker to the client.
    ///
    /// # Arguments
    ///
    /// * `entry` - The tracker entry describing the URL and tier.
    ///
    /// # Returns
    ///
    /// Returns the created tracker handle on success, otherwise a [`TrackerError`].
    pub async fn add_tracker_entry(&self, entry: TrackerEntry) -> Result<TrackerHandle> {
        self.sender
            .send(|tx| TrackerClientCommand::AddTracker {
                entry,
                response: tx,
            })
            .await
            .await
    }

    /// Adds a new tracker to the client on a background task.
    ///
    /// This is the asynchronous "fire-and-forget" variant of
    /// [`TrackerClient::add_tracker_entry`]. Any error is only logged.
    ///
    /// # Arguments
    ///
    /// * `entry` - The tracker entry describing the URL and tier.
    pub async fn add_tracker_async(&self, entry: TrackerEntry) {
        self.sender
            .fire_and_forget(TrackerClientCommand::AddTracker {
                entry,
                response: Reply::empty(),
            })
            .await;
    }

    /// Announces an event for the given torrent to all trackers.
    ///
    /// # Returns
    ///
    /// Returns the aggregated announcement response result from all trackers.
    pub async fn announce_all(
        &self,
        info_hash: &InfoHash,
        event: AnnounceEvent,
    ) -> AnnouncementResult {
        let start_time = Instant::now();
        let result = self
            .sender
            .send(|tx| TrackerClientCommand::AnnounceAll {
                info_hash: info_hash.clone(),
                event,
                response: tx,
            })
            .await
            .await
            .unwrap_or_default();
        let elapsed = start_time.elapsed();
        trace!(
            "Announced to all trackers in {:.3} seconds",
            elapsed.as_secs_f64()
        );
        result
    }

    /// Announces the given event for a specific torrent to the specified tracker.
    ///
    /// # Returns
    ///
    /// Returns the announcement result from that tracker or a [`TrackerError`].
    pub async fn announce(
        &self,
        handle: TrackerHandle,
        info_hash: &InfoHash,
        event: AnnounceEvent,
    ) -> Result<AnnouncementResult> {
        self.sender
            .send(|tx| TrackerClientCommand::Announce {
                handle,
                info_hash: info_hash.clone(),
                event,
                response: tx,
            })
            .await
            .await
    }

    /// Announces an event for the given torrent to all trackers.
    ///
    /// This method will spawn the announcement task and return immediately
    /// without waiting for the responses.
    pub async fn make_announcement_to_all(&self, info_hash: &InfoHash, event: AnnounceEvent) {
        self.sender
            .fire_and_forget(TrackerClientCommand::AnnounceAll {
                info_hash: info_hash.clone(),
                event,
                response: Reply::empty(),
            })
            .await;
    }

    /// Announces an event for the given torrent to the specified tracker.
    ///
    /// This method will spawn the announcement task and return immediately
    /// without waiting for the response.
    pub async fn make_announcement(
        &self,
        handle: TrackerHandle,
        info_hash: &InfoHash,
        event: AnnounceEvent,
    ) {
        self.sender
            .fire_and_forget(TrackerClientCommand::Announce {
                handle,
                info_hash: info_hash.clone(),
                event,
                response: Reply::empty(),
            })
            .await;
    }

    /// Scrapes all trackers for stats about the given [`InfoHash`].
    ///
    /// The results from all trackers are aggregated per file.
    ///
    /// # Errors
    ///
    /// Returns [`TrackerError::NoTrackers`] if no trackers are registered.
    pub async fn scrape(&self, info_hash: &InfoHash) -> Result<ScrapeResult> {
        let mut result = ScrapeResult::default();

        let trackers = self
            .sender
            .send(|tx| TrackerClientCommand::GetActiveTrackers { response: tx })
            .await
            .await?;
        if trackers.is_empty() {
            return Err(TrackerError::NoTrackers);
        }

        let scrape_results: Vec<Result<ScrapeResult>> =
            future::join_all(trackers.into_iter().map(|tracker| {
                let tracker_handle = tracker.handle();
                async move {
                    self.sender
                        .send(|tx| TrackerClientCommand::Scrape {
                            handle: tracker_handle,
                            info_hash: info_hash.clone(),
                            response: tx,
                        })
                        .await
                        .await
                }
            }))
            .await;

        for scrape_result in scrape_results.into_iter() {
            match scrape_result {
                Ok(metrics) => {
                    for (hash, metrics) in metrics.files {
                        let file_metrics = result
                            .files
                            .entry(hash)
                            .or_insert(ScrapeFileMetrics::default());
                        file_metrics.complete += metrics.complete;
                        file_metrics.incomplete += metrics.incomplete;
                        file_metrics.downloaded += metrics.downloaded;
                    }
                }
                Err(e) => debug!("Tracker manager {} failed to scrape tracker, {}", self, e),
            }
        }

        Ok(result)
    }

    /// Starts automatically announcing the torrent with the given info hash.
    ///
    /// This re-enables periodic announcements if they were previously stopped
    /// via [`TrackerClient::stop_announcing`].
    pub async fn start_announcing(&self, info_hash: &InfoHash) {
        self.sender
            .fire_and_forget(TrackerClientCommand::UpdateAnnouncingState {
                info_hash: info_hash.clone(),
                announcing: true,
            })
            .await;
    }

    /// Stops automatically announcing the torrent with the given info hash.
    ///
    /// This does not remove the torrent from the tracker client,
    /// but temporarily disables any new automatic announcements.
    /// Use [`TrackerClient::start_announcing`] to enable automatic announcements again.
    pub async fn stop_announcing(&self, info_hash: &InfoHash) {
        self.sender
            .fire_and_forget(TrackerClientCommand::UpdateAnnouncingState {
                info_hash: info_hash.clone(),
                announcing: false,
            })
            .await;
    }

    /// Returns `true` if the torrent is being automatically announced, else `false`.
    pub async fn is_announcing(&self, info_hash: &InfoHash) -> bool {
        self.sender
            .send(|tx| TrackerClientCommand::GetAnnouncingState {
                info_hash: info_hash.clone(),
                response: tx,
            })
            .await
            .await
            .unwrap_or_default()
    }

    /// Returns `true` if the tracker client is closed and no longer accepts any operations.
    pub fn is_closed(&self) -> bool {
        self.cancellation_token.is_cancelled() || self.sender.is_closed()
    }

    /// Closes the tracker client, resulting in termination of its operations.
    ///
    /// This cancels the internal event loop and closes all managed tracker connections.
    pub fn close(&self) {
        self.cancellation_token.cancel();
    }
}

impl Callback<TrackerClientEvent> for TrackerClient {
    fn subscribe(&self) -> Subscription<TrackerClientEvent> {
        self.callbacks.subscribe()
    }
}

#[derive(Debug)]
enum TrackerClientCommand {
    /// Get the tracker by handle from the client.
    GetTracker {
        handle: TrackerHandle,
        response: Reply<Option<Tracker>>,
    },
    /// Get the tracker by url from the client.
    GetTrackerByUrl {
        url: Url,
        response: Reply<Option<Tracker>>,
    },
    /// Get all trackers from the client.
    GetTrackers { response: Reply<Vec<Tracker>> },
    /// Get all active tracker from the client.
    GetActiveTrackers { response: Reply<Vec<Tracker>> },
    /// Get the number of trackers in the client.
    GetTrackersLen { response: Reply<usize> },
    /// Add a new tracker to the client.
    AddTracker {
        entry: TrackerEntry,
        response: Reply<Result<TrackerHandle>>,
    },
    /// Check if the given url is already known.
    IsUrlKnown { url: Url, response: Reply<bool> },
    /// Get all known tracker urls from the client.
    GetTrackerUrls { response: Reply<Vec<Url>> },
    /// Get the number of torrents known to the client.
    GetTorrentsLen { response: Reply<usize> },
    /// Add a new tracked torrent to the client.
    AddTorrent {
        peer_id: PeerId,
        peer_port: u16,
        info_hash: InfoHash,
        metrics: Metrics,
        response: Reply<Result<()>>,
    },
    /// Remove a tracked torrent from the client.
    RemoveTorrent { info_hash: InfoHash },
    /// Get the already discovered peers for the given info hash.
    DiscoveredTorrentPeers {
        info_hash: InfoHash,
        response: Reply<Option<HashSet<SocketAddr>>>,
    },
    /// Announce the event to all active trackers.
    AnnounceAll {
        info_hash: InfoHash,
        event: AnnounceEvent,
        response: Reply<AnnouncementResult>,
    },
    /// Announce the event to the specified tracker.
    Announce {
        handle: TrackerHandle,
        info_hash: InfoHash,
        event: AnnounceEvent,
        response: Reply<Result<AnnouncementResult>>,
    },
    /// Update the automatically announcing state of the given torrent.
    UpdateAnnouncingState {
        info_hash: InfoHash,
        announcing: bool,
    },
    /// Returns the current automatically announcing state of the given torrent.
    GetAnnouncingState {
        info_hash: InfoHash,
        response: Reply<bool>,
    },
    /// Scrape the info hash from the given tracker.
    Scrape {
        handle: TrackerHandle,
        info_hash: InfoHash,
        response: Reply<Result<ScrapeResult>>,
    },
}

/// Inner implementation of the tracker client.
///
/// This type is reference-counted and shared by the public [`TrackerClient`].
#[derive(Debug, Display)]
#[display("{}", handle)]
struct InnerClient {
    /// The unique handle of this client.
    handle: TrackerHandle,
    /// Active trackers managed by this client.
    trackers: Vec<Tracker>,
    /// The torrents being tracked by this client.
    torrents: HashMap<InfoHash, TrackerTorrent>,
    /// The timeout for tracker connections.
    connection_timeout: Duration,
    /// The pending outgoing connections to trackers.
    pending_connections: JoinSet<Option<Tracker>>,
    /// Callback dispatcher used to notify subscribers of client events.
    callbacks: MultiThreadedCallback<TrackerClientEvent>,
    /// Aggregated tracker client metrics.
    metrics: TrackerClientMetrics,
    /// Cancellation token used to stop the client event loop and background tasks.
    cancellation_token: CancellationToken,
}

impl InnerClient {
    fn new(connection_timeout: Duration) -> Self {
        Self {
            handle: Default::default(),
            trackers: Default::default(),
            torrents: Default::default(),
            connection_timeout,
            pending_connections: Default::default(),
            callbacks: MultiThreadedCallback::new(),
            metrics: Default::default(),
            cancellation_token: Default::default(),
        }
    }

    /// Run the main event loop of the tracker client.
    ///
    /// This loop processes commands, performs automatic announcements, and updates stats
    /// until the cancellation token is triggered.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn run(&mut self, mut command_receiver: ChannelReceiver<TrackerClientCommand>) {
        let mut announcement_tick = time::interval(DEFAULT_ANNOUNCEMENT_INTERVAL);
        let mut stats_interval = time::interval(STATS_INTERVAL);

        loop {
            select! {
                _ = self.cancellation_token.cancelled() => break,
                Some(command) = command_receiver.recv() => self.on_command(command).await,
                resp = self.pending_connections.join_next(), if !self.pending_connections.is_empty() => {
                    if let Some(tracker) = resp.and_then(|e| e.ok()).flatten() {
                        self.add_tracker(tracker);
                    }
                },
                _ = announcement_tick.tick() => self.do_automatic_announcements().await,
                _ = stats_interval.tick() => self.update_stats().await,
            }
        }

        self.announce_all_stopped().await;
        self.close().await;
        debug!("Tracker client {} main loop has stopped", self);
    }

    async fn on_command(&mut self, command: TrackerClientCommand) {
        match command {
            TrackerClientCommand::GetTracker { handle, response } => {
                response.send(self.find_tracker(handle).cloned())
            }
            TrackerClientCommand::GetTrackerByUrl { url, response } => response.send(
                self.trackers
                    .iter()
                    .find(|tracker| tracker.url() == &url)
                    .cloned(),
            ),
            TrackerClientCommand::GetActiveTrackers { response } => {
                response.send(self.active_trackers().await.cloned().collect_vec())
            }
            TrackerClientCommand::GetTrackers { response } => response.send(self.trackers.clone()),
            TrackerClientCommand::GetTrackersLen { response } => response.send(self.trackers.len()),
            TrackerClientCommand::AddTracker { entry, response } => {
                self.create_tracker_from_entry(entry, response).await;
            }
            TrackerClientCommand::IsUrlKnown { url, response } => {
                response.send(self.is_tracker_url_known(&url))
            }
            TrackerClientCommand::GetTrackerUrls { response } => response.send(
                self.trackers
                    .iter()
                    .map(|tracker| tracker.url())
                    .cloned()
                    .collect(),
            ),
            TrackerClientCommand::GetTorrentsLen { response } => response.send(self.torrents.len()),
            TrackerClientCommand::AddTorrent {
                peer_id,
                peer_port,
                info_hash,
                metrics,
                response,
            } => response.send(self.add_torrent(peer_id, peer_port, info_hash, metrics)),
            TrackerClientCommand::RemoveTorrent { info_hash } => {
                self.remove_torrent(info_hash);
            }
            TrackerClientCommand::DiscoveredTorrentPeers {
                info_hash,
                response,
            } => response.send(self.discovered_peers(&info_hash)),
            TrackerClientCommand::AnnounceAll {
                info_hash,
                event,
                response,
            } => response.send(self.announce_all(&info_hash, event).await),
            TrackerClientCommand::Announce {
                handle,
                info_hash,
                event,
                response,
            } => response.send(self.announce(handle, &info_hash, event).await),
            TrackerClientCommand::UpdateAnnouncingState {
                info_hash,
                announcing,
            } => {
                self.update_torrent_announcing_state(info_hash.clone(), announcing);
            }
            TrackerClientCommand::GetAnnouncingState {
                info_hash,
                response,
            } => {
                response.send(
                    self.torrents
                        .get(&info_hash)
                        .map(|torrent| torrent.is_announcing)
                        .unwrap_or_default(),
                );
            }
            TrackerClientCommand::Scrape {
                handle,
                info_hash,
                response,
            } => match self.find_tracker(handle) {
                None => response.send(Err(TrackerError::InvalidHandle(handle))),
                Some(tracker) => response.send(tracker.scrape(&[info_hash]).await),
            },
        }
    }

    fn update_torrent_announcing_state(&mut self, info_hash: InfoHash, is_announcing: bool) {
        if let Some(torrent) = self.torrents.get_mut(&info_hash) {
            torrent.is_announcing = is_announcing;
        }
    }

    fn find_tracker(&self, handle: TrackerHandle) -> Option<&Tracker> {
        self.trackers
            .iter()
            .find(|tracker| tracker.handle() == handle)
    }

    /// Returns the discovered peers for the given torrent.
    fn discovered_peers(&self, info_hash: &InfoHash) -> Option<HashSet<SocketAddr>> {
        self.torrents
            .get(info_hash)
            .map(|torrent| torrent.peers.clone())
    }

    /// Returns all active trackers of the client.
    async fn active_trackers(&self) -> impl Iterator<Item = &Tracker> {
        future::join_all(
            self.trackers
                .iter()
                .map(|tracker| async move { (tracker, tracker.state().await) }),
        )
        .await
        .into_iter()
        .filter(|(_, state)| *state == TrackerState::Active)
        .map(|(tracker, _)| tracker)
    }

    fn add_torrent(
        &mut self,
        peer_id: PeerId,
        peer_port: u16,
        info_hash: InfoHash,
        metrics: Metrics,
    ) -> Result<()> {
        // early exit if the port is invalid
        if peer_port == 0 {
            debug!(
                "Tracker client {} failed to track torrent {}, invalid port",
                self, info_hash
            );
            return Err(TrackerError::InvalidPort(peer_port));
        }

        // check if the given info hash if unique within the registered torrents
        // if not, we ignore this registration
        if !self.torrents.contains_key(&info_hash) {
            let info_hash_txt = info_hash.to_string();
            self.torrents.insert(
                info_hash.clone(),
                TrackerTorrent {
                    peer_id,
                    peer_port,
                    metrics,
                    peers: Default::default(),
                    is_announcing: true,
                },
            );
            debug!("Tracker client {} added torrent {}", self, info_hash_txt);
        }

        Ok(())
    }

    fn remove_torrent(&mut self, info_hash: InfoHash) {
        if let Some(_) = self.torrents.remove(&info_hash) {
            debug!("Tracker client {} removed torrent {}", self, info_hash);
        }
    }

    /// Checks if the given URL is already registered/known.
    fn is_tracker_url_known(&self, url: &Url) -> bool {
        self.trackers.iter().any(|tracker| tracker.url() == url)
    }

    /// Tries to create a new tracker for the given entry.
    ///
    /// The URL of the entry must not already be known. On success,
    /// the created tracker is added to the client.
    async fn create_tracker_from_entry(
        &mut self,
        entry: TrackerEntry,
        response: Reply<Result<TrackerHandle>>,
    ) {
        // if the url is already known, reject the request to create the tracker
        let url_already_exists = self.is_tracker_url_known(&entry.url);
        if url_already_exists {
            response.send(Err(TrackerError::DuplicateUrl(entry.url)));
            return;
        }

        let handle = self.handle;
        let timeout = self.connection_timeout.clone();
        self.pending_connections.spawn(async move {
            let mut builder = Tracker::builder();
            let result = select! {
                _ = time::sleep(timeout) => Err(TrackerError::Io(io::Error::new(io::ErrorKind::TimedOut, "connection timed out"))),
                tracker = builder
                    .url(entry.url)
                    .tier(entry.tier)
                    .build() => tracker,
            };

            match result {
                Ok(tracker) => {
                    response.send(Ok(tracker.handle()));
                    Some(tracker)
                }
                Err(e) => {
                    debug!(
                        "Tracker client {} failed to create tracker from entry, {}",
                        handle, e
                    );
                    response.send(Err(e));
                    None
                }
            }
        });
    }

    /// Adds the given tracker to the tracker's pool.
    fn add_tracker(&mut self, tracker: Tracker) {
        // drop the tracker if it already exists
        // this can happen if the tracker was added twice concurrently
        if self.trackers.iter().any(|e| e.url() == tracker.url()) {
            return;
        }

        let handle = tracker.handle();
        let tracker_info = tracker.to_string();
        self.trackers.push(tracker);
        debug!("Tracker {} has been added to {}", tracker_info, self);
        self.callbacks
            .invoke(TrackerClientEvent::TrackerAdded(handle));
    }

    async fn announce(
        &mut self,
        handle: TrackerHandle,
        info_hash: &InfoHash,
        event: AnnounceEvent,
    ) -> Result<AnnouncementResult> {
        let tracker = self
            .trackers
            .iter()
            .find(|e| e.handle() == handle)
            .ok_or(TrackerError::InvalidHandle(handle))?;
        let torrent = self
            .torrents
            .get_mut(info_hash)
            .ok_or(TrackerError::InfoHashNotFound(info_hash.clone()))?;

        let result = Self::announce_tracker(
            tracker,
            info_hash,
            event,
            torrent.peer_id,
            torrent.peer_port,
            torrent.metrics.completed_size.total(),
            torrent.metrics.bytes_remaining(),
        )
        .await
        .map(|e| AnnouncementResult {
            total_leechers: e.leechers,
            total_seeders: e.seeders,
            peers: e.peers,
        })?;
        Self::add_peers(info_hash, result.peers.as_slice(), torrent, &self.callbacks);

        Ok(result)
    }

    async fn announce_all(
        &mut self,
        info_hash: &InfoHash,
        event: AnnounceEvent,
    ) -> AnnouncementResult {
        // early exit if the torrent is not tracked
        if !self.torrents.contains_key(info_hash) {
            warn!(
                "Tracker {} failed to announce event, torrent {} info hash not found",
                self, info_hash
            );
            return AnnouncementResult::default();
        }

        let mut result = AnnouncementResult::default();
        let mut total_peers = 0;

        // start announcing the given hash to each tracker simultaneously
        let futures: Vec<_> = {
            let torrent = &self.torrents[info_hash];
            self.active_trackers()
                .await
                .map(|tracker| {
                    Self::announce_tracker(
                        tracker,
                        info_hash,
                        event,
                        torrent.peer_id,
                        torrent.peer_port,
                        torrent.metrics.completed_size.total(),
                        torrent.metrics.bytes_remaining(),
                    )
                })
                .collect()
        };

        // wait for all responses to complete
        let responses = future::join_all(futures).await;
        let torrent = match self.torrents.get_mut(info_hash) {
            Some(torrent) => torrent,
            None => unreachable!(),
        };
        for response in responses {
            match response {
                Ok(response) => {
                    result.total_leechers += response.leechers;
                    result.total_seeders += response.seeders;
                    result.peers.extend_from_slice(response.peers.as_slice());

                    total_peers += Self::add_peers(
                        info_hash,
                        response.peers.as_slice(),
                        torrent,
                        &self.callbacks,
                    );
                }
                Err(e) => debug!(
                    "Failed to announce info hash {:?} to tracker, {}",
                    info_hash, e
                ),
            }
        }

        info!(
            "Discovered a total of {} peers for {}",
            total_peers, info_hash
        );
        result
    }

    async fn announce_all_stopped(&mut self) {
        let mut futures = Vec::with_capacity(self.trackers.len() * self.torrents.len());

        for (info_hash, torrent) in self.torrents.iter() {
            futures.extend(self.trackers.iter().map(|tracker| {
                Self::announce_tracker(
                    tracker,
                    &info_hash,
                    AnnounceEvent::Stopped,
                    torrent.peer_id,
                    torrent.peer_port,
                    torrent.metrics.completed_size.total(),
                    torrent.metrics.bytes_remaining(),
                )
            }));
        }

        for response in future::join_all(futures).await {
            if let Err(e) = response {
                debug!("Failed announce stop event to tracker, {}", e);
            }
        }
    }

    /// Performs automatic announcements to all trackers periodically.
    ///
    /// This method is called by the periodic task loop and respects the
    /// per-tracker announcement interval and last announcement timestamp.
    async fn do_automatic_announcements(&self) {
        let now = Instant::now();

        for (info_hash, torrent) in self
            .torrents
            .iter()
            .filter(|(_, torrent)| torrent.is_announcing)
        {
            for tracker in self.active_trackers().await {
                let interval = tracker.announcement_interval().await;
                let last_announcement = tracker.last_announcement().await;
                let delta = now - last_announcement;

                if delta.as_secs() >= interval {
                    if let Err(err) = Self::announce_tracker(
                        tracker,
                        &info_hash,
                        AnnounceEvent::Started,
                        torrent.peer_id,
                        torrent.peer_port,
                        torrent.metrics.completed_size.total(),
                        torrent.metrics.bytes_remaining(),
                    )
                    .await
                    {
                        debug!("Tracker {} failed to make announcement, {}", tracker, err);
                    }
                }
            }
        }
    }

    /// Updates metrics and emits a [`TrackerClientEvent::Stats`] event.
    ///
    /// This aggregates tracker metrics into the client metrics and ticks
    /// both tracker and client metric time windows.
    async fn update_stats(&self) {
        for tracker in self.trackers.iter() {
            let tracker_metrics = tracker.metrics();

            self.metrics.bytes_in.inc_by(tracker_metrics.bytes_in.get());
            self.metrics
                .bytes_out
                .inc_by(tracker_metrics.bytes_out.get());

            tracker.tick(STATS_INTERVAL);
        }

        self.callbacks
            .invoke(TrackerClientEvent::Stats(self.metrics.snapshot()));
        self.metrics.tick(STATS_INTERVAL);
    }

    /// Closes all tracker connections managed by this client.
    async fn close(&mut self) {
        let futures = self
            .trackers
            .drain(..)
            .map(|tracker| {
                let timeout = self.connection_timeout.clone();
                async move {
                    select! {
                        _ = time::sleep(timeout) => {
                            debug!("Tracker {} failed to close connection, time-out", tracker.handle());
                        },
                        _ = tracker.close() => {},
                    }
                }
            })
            .collect_vec();

        futures::future::join_all(futures).await;
    }

    /// Adds one or more discovered peers to the tracker client.
    ///
    /// This will only add unique peer addresses and filters out any duplicate
    /// addresses that have already been discovered for the torrent.
    ///
    /// # Returns
    ///
    /// The number of newly added unique peer addresses.
    fn add_peers(
        info_hash: &InfoHash,
        peers: &[SocketAddr],
        torrent: &mut TrackerTorrent,
        callbacks: &MultiThreadedCallback<TrackerClientEvent>,
    ) -> usize {
        trace!("Discovered a total of {} peers, {:?}", peers.len(), peers);
        let mut unique_new_peer_addrs = Vec::new();

        for peer in peers.into_iter() {
            if !torrent.peers.contains(peer) {
                torrent.peers.insert(peer.clone());
                unique_new_peer_addrs.push(peer.clone());
            }
        }

        debug!(
            "Discovered a total of {} new peers",
            unique_new_peer_addrs.len()
        );
        let total_peers = unique_new_peer_addrs.len();
        if total_peers > 0 {
            callbacks.invoke(TrackerClientEvent::PeersDiscovered(
                info_hash.clone(),
                unique_new_peer_addrs,
            ));
        }

        total_peers
    }

    async fn announce_tracker(
        tracker: &Tracker,
        info_hash: &InfoHash,
        event: AnnounceEvent,
        peer_id: PeerId,
        peer_port: u16,
        bytes_completed: u64,
        bytes_remaining: u64,
    ) -> Result<AnnouncementResponse> {
        trace!("Announcing event {} to tracker {}", event, tracker);
        let announce = Announcement {
            info_hash: info_hash.clone(),
            peer_id,
            peer_port,
            event,
            bytes_completed,
            bytes_remaining,
        };

        match tracker.announce(announce).await {
            Ok(response) => {
                debug!(
                    "Tracker {} announcement found {} peers",
                    tracker,
                    response.peers.len()
                );
                Ok(response)
            }
            Err(e) => {
                warn!(
                    "Announcement of event {} failed for tracker {}, {:?}",
                    event, tracker, e
                );
                Err(e)
            }
        }
    }
}

/// A torrent peer registered with the tracker.
#[derive(Debug, PartialEq)]
struct TrackerTorrent {
    /// The unique peer id of the torrent
    peer_id: PeerId,
    /// The port the torrent is listening on to accept incoming connections
    peer_port: u16,
    /// The discovered peers for this torrent by the tracker
    peers: HashSet<SocketAddr>,
    /// A reference to the torrent metrics
    metrics: Metrics,
    /// Indicates if the torrent peer should be announced to the trackers.
    is_announcing: bool,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::tracker::TrackerServer;
    use crate::tracker::UdpServer;
    use std::net::Ipv4Addr;
    use std::str::FromStr;
    use tokio::sync::mpsc::unbounded_channel;
    use url::Url;

    mod add_torrent {
        use super::*;

        #[tokio::test]
        async fn test_valid_torrent() {
            init_logger!();
            let peer_id = PeerId::new();
            let peer_port = 6881;
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let manager = TrackerClient::new(Duration::from_secs(1));

            // add a new torrent
            let result = manager
                .add_torrent(peer_id, peer_port, info_hash.clone(), Metrics::new())
                .await;
            assert_eq!(Ok(()), result);

            // verify that the torrent was added
            let result = manager.torrents_len().await;
            assert_eq!(1, result, "expected the torrent to have been registered");

            {
                let _ = manager
                    .add_torrent(PeerId::new(), peer_port, info_hash, Metrics::new())
                    .await;
                let result = manager.torrents_len().await;
                assert_eq!(
                    1, result,
                    "expected the torrent to not have been added as duplicate"
                );
            }
        }

        #[tokio::test]
        async fn test_invalid_port() {
            init_logger!();
            let info_hash =
                InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
            let manager = TrackerClient::new(Duration::from_secs(1));

            let result = manager
                .add_torrent(PeerId::new(), 0, info_hash, Metrics::new())
                .await;

            assert_eq!(Err(TrackerError::InvalidPort(0)), result);
        }
    }

    mod get {
        use super::*;

        #[tokio::test]
        async fn test_get_by_handle() {
            init_logger!();
            let server = TrackerServer::new().await.unwrap();
            let client = TrackerClient::new(Duration::from_secs(2));

            // add the tracker to the client
            let handle = client
                .add_tracker_entry(TrackerEntry {
                    tier: 0,
                    url: server.url().clone(),
                })
                .await
                .expect("expected the tracker to have been added");

            // retrieve the tracker
            let result = client
                .get(&handle)
                .await
                .expect("expected the tracker to have been found");
            assert_eq!(handle, result.handle(), "expected the handle to match");
        }

        #[tokio::test]
        async fn test_get_by_url() {
            init_logger!();
            let server = TrackerServer::new().await.unwrap();
            let client = TrackerClient::new(Duration::from_secs(2));

            // add the tracker to the client
            let url = server.url();
            let result = client
                .add_tracker_entry(TrackerEntry {
                    tier: 0,
                    url: url.clone(),
                })
                .await;
            assert!(result.is_ok(), "expected Ok(), but got {:?}", result);

            // retrieve the tracker
            let result = client
                .get_by_url(&url)
                .await
                .expect("expected the tracker to have been found");
            assert_eq!(url, result.url(), "expected the url to match");
        }
    }

    #[tokio::test]
    async fn test_remove_torrent() {
        init_logger!();
        let info_hash =
            InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
        let manager = TrackerClient::new(Duration::from_secs(2));

        // try to remove a non-existing torrent
        manager.remove_torrent(&info_hash).await;

        {
            manager
                .add_torrent(PeerId::new(), 6881, info_hash.clone(), Metrics::new())
                .await
                .unwrap();
            let result = manager.torrents_len().await;
            assert_eq!(1, result, "expected the torrent to have been registered");
        }

        {
            manager.remove_torrent(&info_hash).await;
            assert_timeout!(
                Duration::from_millis(500),
                manager.torrents_len().await == 0,
                "expected the torrent to have been removed"
            );
        }
    }

    #[tokio::test]
    async fn test_tracker_manager_announce_all() {
        init_logger!();
        let peer_id = PeerId::new();
        let info_hash =
            InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
        let server = TrackerServer::new().await.unwrap();
        let manager = TrackerClient::new(Duration::from_secs(3));

        // add a dummy peer to the server
        server
            .add_peer(
                info_hash.clone(),
                SocketAddr::from((Ipv4Addr::LOCALHOST, 6881)),
                PeerId::new(),
                6881,
                false,
            )
            .await;

        // add the tracker to the tracker client
        let result = manager
            .add_torrent(peer_id, 6881, info_hash.clone(), Metrics::new())
            .await;
        assert!(
            result.is_ok(),
            "expected Ok() for add_torrent, but got {:?}",
            result
        );

        // add the tracker entry to the client
        let entry = TrackerEntry {
            tier: 0,
            url: server.url().clone(),
        };
        let result = manager.add_tracker_entry(entry).await;
        assert!(
            result.is_ok(),
            "expected Ok() for add_tracker_entry, but got {:?}",
            result
        );

        let result = manager
            .announce_all(&info_hash, AnnounceEvent::Started)
            .await;
        assert_eq!(1, result.total_leechers, "expected 1 leecher");
        assert_eq!(0, result.total_seeders, "expected 0 seeders");
        assert_eq!(
            1,
            result.peers.len(),
            "expected the peer to have been found"
        );
    }

    #[tokio::test]
    async fn test_tracker_manager_scrape() {
        init_logger!();
        let peer_id = PeerId::new();
        let info_hash =
            InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
        let server =
            TrackerServer::with_listeners(vec![Box::new(UdpServer::with_port(0).await.unwrap())])
                .unwrap();
        let manager = TrackerClient::new(Duration::from_secs(3));

        // register the torrent
        manager
            .add_torrent(peer_id, 6881, info_hash.clone(), Metrics::new())
            .await
            .unwrap();

        // add the tracker server entry
        let entry = TrackerEntry {
            tier: 0,
            url: server.url().clone(),
        };
        manager.add_tracker_entry(entry).await.unwrap();
        let result = manager
            .scrape(&info_hash)
            .await
            .expect("expected the scrape to succeed");

        assert_eq!(
            1,
            result.files.len(),
            "expected the scrape result to match the torrent"
        );
    }

    #[tokio::test]
    async fn test_discovered_peers() {
        init_logger!();
        let info_hash =
            InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
        let peer_addr = SocketAddr::from(([127, 0, 0, 1], 6882));
        let server = TrackerServer::new().await.unwrap();
        let manager = TrackerClient::new(Duration::from_secs(2));

        // add a new tracker
        let result = manager
            .add_tracker_entry(TrackerEntry {
                tier: 0,
                url: server.url().clone(),
            })
            .await;
        assert!(result.is_ok(), "expected Ok(), but got {:?}", result);

        // start tracking the torrent
        let result = manager
            .add_torrent(PeerId::new(), 10999, info_hash.clone(), Metrics::new())
            .await;
        assert!(result.is_ok(), "expected Ok(), but got {:?}", result);

        // add the peer to the server
        server
            .add_peer(
                info_hash.clone(),
                peer_addr.clone(),
                PeerId::new(), // this needs to be different torrent Peer ID added to the manager
                peer_addr.port(),
                false,
            )
            .await;

        // announce the torrent to the trackers
        let result = manager
            .announce_all(&info_hash, AnnounceEvent::Started)
            .await;
        assert_eq!(
            1, result.total_leechers,
            "expected 1 leecher to have been discovered during announcement"
        );

        // request the cached discovered peers
        let result = manager
            .discovered_peers(&info_hash)
            .await
            .expect("expected the torrent to have been tracked");
        assert_eq!(1, result.len(), "expected 1 peer to have been discovered");
        assert_eq!(peer_addr, result[0], "expected the peer to be discovered");
    }

    #[tokio::test]
    async fn test_add_callback() {
        init_logger!();
        let (tx, mut rx) = unbounded_channel();
        let server =
            TrackerServer::with_listeners(vec![Box::new(UdpServer::with_port(0).await.unwrap())])
                .unwrap();
        let entry = TrackerEntry {
            tier: 0,
            url: server.url().clone(),
        };
        let manager = TrackerClient::new(Duration::from_secs(1));

        let mut receiver = manager.subscribe();
        tokio::spawn(async move {
            while let Ok(event) = receiver.recv().await {
                if let TrackerClientEvent::TrackerAdded(_) = &*event {
                    tx.send((*event).clone()).unwrap();
                    break;
                }
            }
        });

        manager
            .add_tracker_entry(entry)
            .await
            .expect("expected the tracker to have been created");

        let result = timeout!(
            Duration::from_millis(750),
            rx.recv(),
            "expected to receive an event"
        )
        .unwrap();
        if let TrackerClientEvent::TrackerAdded(handle) = result {
            let result = manager
                .trackers()
                .await
                .into_iter()
                .any(|e| e.handle() == handle);
            assert!(
                result,
                "expected tracker {} to have been present within the managed",
                handle
            );
        } else {
            assert!(
                false,
                "expected TrackerManagerEvent::TrackerAdded, got {:?} instead",
                result
            );
        }
    }

    #[tokio::test]
    async fn test_start_stop_announcing() {
        init_logger!();
        let peer_id = PeerId::new();
        let peer_port = 6881;
        let info_hash =
            InfoHash::from_str("urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7").unwrap();
        let manager = TrackerClient::new(Duration::from_secs(1));

        let result = manager
            .add_torrent(peer_id, peer_port, info_hash.clone(), Metrics::new())
            .await;
        assert_eq!(Ok(()), result, "expected the torrent to have been added");

        manager.stop_announcing(&info_hash).await;
        assert_timeout!(
            Duration::from_millis(500),
            manager.is_announcing(&info_hash).await == false,
            "expected the torrent to be no longer announcing"
        );

        manager.start_announcing(&info_hash).await;
        assert_timeout!(
            Duration::from_millis(500),
            manager.is_announcing(&info_hash).await == true,
            "expected the torrent to be no longer announcing"
        );
    }

    #[tokio::test]
    async fn test_drop() {
        init_logger!();
        let url = Url::parse("udp://tracker.opentrackr.org:1337").unwrap();
        let manager = TrackerClient::new(Duration::from_secs(1));

        manager
            .add_tracker_async(TrackerEntry { tier: 0, url })
            .await;
        drop(manager);
    }
}