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
use crate::channel::ChannelSender;
use crate::operation::TorrentOperationResult;
use crate::peer::extension::HolepunchExtension;
use crate::peer::webseed::HttpPeer;
use crate::peer::{extension, BitTorrentPeer, CloseReason, Peer, PeerDiscovery};
use crate::torrent::InnerTorrent;
use crate::torrent_data::DataPool;
use crate::{Result, TorrentCommand, TorrentContext, TorrentError, TorrentMetadata};
use futures::FutureExt;
use itertools::Itertools;
use log::{debug, trace, warn};
use std::collections::HashMap;
use std::fmt::Debug;
use std::io;
use std::net::SocketAddr;
use std::time::{Duration, Instant};
use tokio::sync::mpsc::{channel, Receiver, Sender};
use tokio::task::JoinSet;
use tokio::time::timeout;
use url::Url;

const BURST_DURATION: Duration = Duration::from_secs(10);
const HOLEPUNCH_TIMEOUT: Duration = Duration::from_secs(6);

/// Establishes additional peer connections for the torrent.
pub struct ConnectPeersOperation {
    initialized: bool,
    /// Indicates whether webseed connections are enabled for the torrent.
    webseeds_enabled: bool,
    /// The available torrent webseeds.
    webseeds: HashMap<SocketAddr, Vec<Url>>,
    /// The maximum amount of in-flight peer connections being established
    max_in_flight: usize,
    /// Indicates the time since the operation started bursting the initial connections
    bursting_since: Option<Instant>,
    /// The in-flight peer-webseed connections
    in_flight: JoinSet<()>,
    /// Indicates whether HolePunching is supported for the torrent.
    holepunch_supported: bool,
    /// The sender for HolePunching requests.
    holepunch_sender: Sender<SocketAddr>,
    /// The receiver for HolePunching requests.
    holepunch_receiver: Receiver<SocketAddr>,
    /// The pending hole punch requests.
    holepunch_queue: JoinSet<(SocketAddr, Option<extension::Error>)>,
}

impl ConnectPeersOperation {
    pub fn new(webseeds_enabled: bool) -> Self {
        let (tx, rx) = channel(32);
        Self {
            initialized: false,
            webseeds_enabled,
            webseeds: Default::default(),
            max_in_flight: 0,
            bursting_since: None,
            in_flight: Default::default(),
            holepunch_supported: false,
            holepunch_sender: tx,
            holepunch_receiver: rx,
            holepunch_queue: Default::default(),
        }
    }

    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    pub async fn execute(
        &mut self,
        context: &mut TorrentContext,
        peer_discoveries: &[PeerDiscovery],
    ) -> TorrentOperationResult {
        self.initialize(context).await;
        self.poll_in_flight(context);
        self.poll_holepunches(context);

        let wanted_connections = context.remaining_peer_connections_needed().await;
        if wanted_connections > 0 {
            self.update_max_in_flight(context);
            self.execute_pending_holepunches(context).await;

            // burst the initial connections if needed
            self.burst(context);

            self.create_additional_peer_connections(wanted_connections, context, peer_discoveries)
                .await;
        }

        TorrentOperationResult::Continue
    }

    /// Poll the currently in-flight peer connections for completion.
    fn poll_in_flight(&mut self, context: &TorrentContext) {
        while let Some(res) = self.in_flight.join_next().now_or_never().flatten() {
            match res {
                Ok(()) => {}
                Err(e) => warn!("Torrent {} peer connection failed, {}", context, e),
            }
        }
    }

    /// Poll the pending holepunch requests.
    fn poll_holepunches(&mut self, context: &mut TorrentContext) {
        while let Some(res) = self.holepunch_queue.join_next().now_or_never().flatten() {
            match res {
                Ok((addr, err)) => {
                    context.peer_pool_mut().peer_punched(&addr, err.is_none());
                    if let Some(err) = err {
                        debug!("Torrent {} failed to punch {}, {}", context, addr, err);
                    }
                }
                Err(_) => break,
            }
        }
    }

    /// Initialize the operation.
    async fn initialize(&mut self, context: &TorrentContext) {
        if self.initialized {
            return;
        }

        self.create_webseed_urls(context);
        self.holepunch_supported = context.is_extension_enabled(HolepunchExtension::NAME);
        self.initialized = true;
    }

    /// Create the webseed url cache from the torrent context.
    fn create_webseed_urls(&mut self, torrent: &TorrentContext) {
        let metadata = torrent.metadata();

        let url_iter = metadata.url_list.iter().flatten();
        let http_seed_iter = metadata.http_seeds.iter().flatten();

        self.webseeds = url_iter
            .chain(http_seed_iter)
            .flat_map(|url| Self::parse_url(torrent, url))
            .filter_map(|url| match Self::resolve_url(&url) {
                Ok(addr) => Some((addr, url)),
                Err(e) => {
                    debug!("Torrent {} failed to resolve webseed url, {}", torrent, e);
                    None
                }
            })
            .into_group_map();
    }

    /// Update the available in-flight permits from the latest torrent config.
    fn update_max_in_flight(&mut self, context: &TorrentContext) {
        let config_peers_in_flight = context.config().peers_in_flight;
        if config_peers_in_flight == self.max_in_flight || self.bursting_since.is_some() {
            return;
        }

        self.max_in_flight = config_peers_in_flight;
    }

    /// Execute a burst of initial peer connections, when needed.
    fn burst(&mut self, context: &TorrentContext) {
        if let Some(since) = self.bursting_since {
            if since.elapsed() < BURST_DURATION {
                return;
            }
            // burst window has ended
            // restore the config back to its original torrent config value
            self.max_in_flight = context.config().peers_in_flight;
            self.bursting_since = None;
        }

        // only allow bursting when we have no active peer connections
        if context.active_peer_connections() == 0 {
            trace!("Torrent {} is bursting it's initial connections", context);
            self.max_in_flight = context.config().peers_upper_limit;
            self.bursting_since = Some(Instant::now());
        }
    }

    /// Execute the pending holepunch tasks.
    #[cfg_attr(feature = "tracing", tracing::instrument(skip_all))]
    async fn execute_pending_holepunches(&mut self, context: &mut TorrentContext) {
        let mut peers = None;

        while let Ok(addr) = self.holepunch_receiver.try_recv() {
            // collect the peers once
            let peers = peers.get_or_insert_with(|| {
                context
                    .peer_pool()
                    .peers()
                    .filter_map(|e| match e {
                        Peer::BitTorrent(e) => Some(e.clone()),
                        _ => None,
                    })
                    .collect_vec()
            });

            self.try_holepunch(addr, peers.as_slice(), context).await;
        }
    }

    /// Try to create additional peer connections
    async fn create_additional_peer_connections(
        &mut self,
        mut wanted_connections: usize,
        context: &mut TorrentContext,
        dialers: &[PeerDiscovery],
    ) {
        // try to create webseed peers
        if self.webseeds_enabled {
            self.create_webseed_peers(&mut wanted_connections, context);
        }

        let available_permits = self.max_in_flight.saturating_sub(self.in_flight.len());
        let len = wanted_connections.min(available_permits);
        let peer_addrs = context.peer_pool_mut().new_connection_candidates(len);
        if peer_addrs.is_empty() {
            // early exit when not peer addrs are available
            trace!(
                "Torrent {} has no peer addresses available to establish peer connections",
                context
            );
            return;
        }

        debug!(
            "Torrent {} is establishing {} (of wanted {}, remaining {} addresses) peer connections",
            context,
            peer_addrs.len(),
            wanted_connections,
            context.peer_pool().num_connect_candidates()
        );
        for addr in peer_addrs {
            if let Err(e) = self.create_peer_with_dialers(context, addr, dialers) {
                warn!(
                    "Torrent {} failed to create peer connection to {}, {}",
                    context, addr, e
                );
            }
        }
    }

    fn create_webseed_peers(&mut self, wanted_connections: &mut usize, context: &TorrentContext) {
        if self.webseeds.is_empty() {
            return;
        }

        let available_permits = self.max_in_flight.saturating_sub(self.in_flight.len());
        let new_connections_len = (*wanted_connections).min(available_permits);
        let len = new_connections_len.min(self.webseeds.len());

        // update the wanted connections
        *wanted_connections = wanted_connections.saturating_sub(len);

        let mut picked_webseeds = 0;
        while let Some(addr) = self.webseeds.keys().next().copied() {
            if picked_webseeds >= len {
                break;
            }

            picked_webseeds += 1;
            if let Some((addr, urls)) = self.webseeds.remove_entry(&addr) {
                let torrent = InnerTorrent::new(
                    context.handle(),
                    context.command_sender().clone(),
                    context.callbacks().clone(),
                );
                let data_pool = context.data_pool().clone();
                let metadata = context.metadata().clone();
                let sender = context.command_sender().clone();
                if let Err(e) =
                    self.create_http_peer(addr, urls, torrent, data_pool, metadata, sender)
                {
                    warn!(
                        "Torrent {} failed to create webseed peer connection, {}",
                        context, e
                    );
                }
            }
        }
    }

    /// Try to establish the peer connection through the torrent peer dialers.
    /// This will dial the address for every dialer and create the connection of the first received successful peer connection.
    fn create_peer_with_dialers<'a>(
        &mut self,
        context: &TorrentContext,
        peer_addr: SocketAddr,
        dialers: &[PeerDiscovery],
    ) -> Result<()> {
        // early exit when no dialers are available
        if dialers.is_empty() {
            return Err(TorrentError::Io(io::Error::new(
                io::ErrorKind::Other,
                "no active peer dialers",
            )));
        }

        let handle_info = context.handle();
        let protocol_extensions = context.protocol_extensions();
        let peer_id = context.peer_id();
        let peer_connection_timeout = context.config().peer_connection_timeout;
        let holepunch_sender = self.holepunch_sender.clone();
        let holepunch_supported = self.holepunch_supported;

        debug!(
            "Torrent {} is trying to create new peer connection to {} through {} dialers",
            context,
            peer_addr,
            dialers.len()
        );
        let torrent = InnerTorrent::new(
            context.handle(),
            context.command_sender().clone(),
            context.callbacks().clone(),
        );
        let metadata = context.metadata().clone();
        let peer_port = context.peer_port().copied();
        let peer_client_name = context.config().client_name().to_string();
        let data_pool = context.data_pool().clone();
        let storage = context.storage().clone();
        let dialers = dialers
            .iter()
            .map(|dialer| {
                let protocol = dialer.protocol();
                let extensions = context.extensions(protocol);

                (dialer.clone(), extensions)
            })
            .collect_vec();
        let command_sender = context.command_sender().clone();
        self.in_flight.spawn(async move {
            let mut peer = None;
            for (dialer, extensions) in dialers {
                match dialer
                    .dial(
                        peer_id,
                        peer_addr.clone(),
                        peer_port.clone(),
                        peer_client_name.as_str(),
                        torrent.clone(),
                        metadata.clone(),
                        data_pool.clone(),
                        storage.clone(),
                        protocol_extensions,
                        extensions,
                        peer_connection_timeout,
                    )
                    .await
                {
                    Ok(e) => {
                        peer = Some(e);
                        break;
                    }
                    Err(e) => {
                        debug!(
                            "Torrent {} failed to create peer connection, {}",
                            handle_info, e
                        );
                    }
                }
            }

            match peer {
                None => {
                    if holepunch_supported {
                        let _ = holepunch_sender.send(peer_addr).await;
                    } else {
                        command_sender
                            .fire_and_forget(TorrentCommand::PeerClosed {
                                addr: peer_addr,
                                reason: CloseReason::Timeout,
                            })
                            .await;
                    }
                }
                Some(peer) => {
                    command_sender
                        .fire_and_forget(TorrentCommand::PeerConnected { peer })
                        .await;
                }
            }
        });

        Ok(())
    }

    /// Try to create a new HTTP (webseed) peer.
    fn create_http_peer(
        &mut self,
        addr: SocketAddr,
        urls: Vec<Url>,
        torrent: InnerTorrent,
        data_pool: DataPool,
        metadata: TorrentMetadata,
        sender: ChannelSender<TorrentCommand>,
    ) -> Result<()> {
        let handle_info = torrent.handle();

        self.in_flight.spawn(async move {
            trace!(
                "Torrent {} is creating webseed connection {} for {:?}",
                handle_info,
                addr,
                urls
            );
            match HttpPeer::new(addr, urls, torrent, data_pool, metadata).await {
                Ok(peer) => {
                    sender
                        .fire_and_forget(TorrentCommand::PeerConnected { peer: peer.into() })
                        .await;
                }
                Err(e) => {
                    debug!(
                        "Failed to create http peer connection for torrent {}, {}",
                        handle_info, e
                    );
                }
            }
        });
        Ok(())
    }

    /// Try to HolePunch the target peer.
    async fn try_holepunch(
        &mut self,
        target_addr: SocketAddr,
        peers: &[BitTorrentPeer],
        context: &mut TorrentContext,
    ) {
        let mut punching = false;
        for peer in peers {
            if !timeout(
                Duration::from_millis(200),
                peer.supports_extension(HolepunchExtension::NAME),
            )
            .await
            .unwrap_or_default()
            {
                continue;
            }

            context.peer_pool_mut().peer_punching(&target_addr);
            match timeout(Duration::from_millis(250), peer.holepunch(target_addr)).await {
                Ok(response) => {
                    punching = true;
                    self.holepunch_queue.spawn(async move {
                        let response = timeout(HOLEPUNCH_TIMEOUT, response)
                            .await
                            .map_err(|_| {
                                extension::Error::Io(io::Error::new(
                                    io::ErrorKind::TimedOut,
                                    "holepunch timed-out",
                                ))
                            })
                            .flatten();

                        (target_addr, response.err())
                    });
                }
                Err(e) => {
                    context.peer_pool_mut().peer_punched(&target_addr, false);
                    debug!("Torrent {} failed to start holepunch, {}", context, e);
                }
            }
        }

        // if we're unable to punch the target peer
        // record the initial attempt as a timeout failure
        if !punching {
            context
                .peer_pool_mut()
                .peer_closed(&target_addr, CloseReason::Timeout);
        }
    }

    fn parse_url(context: &TorrentContext, url: &str) -> Option<Url> {
        Url::parse(url)
            .map_err(|e| {
                debug!("Torrent {} has invalid webseed url {}, {}", context, url, e);
                e
            })
            .ok()
    }

    fn resolve_url(url: &Url) -> Result<SocketAddr> {
        url.socket_addrs(|| match url.scheme() {
            "http" => Some(80),
            "https" => Some(443),
            _ => None,
        })
        .unwrap_or(Vec::new())
        .pop()
        .ok_or(TorrentError::Io(io::Error::new(
            io::ErrorKind::HostUnreachable,
            format!("unable to resolve {}", url),
        )))
    }
}

impl Debug for ConnectPeersOperation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("TorrentConnectPeersOperation")
            .field("webseeds_enabled", &self.webseeds_enabled)
            .field("webseed_urls", &self.webseeds)
            .field("max_in_flight", &self.max_in_flight)
            .field("bursting_since", &self.bursting_since)
            .finish()
    }
}

impl Drop for ConnectPeersOperation {
    fn drop(&mut self) {
        self.in_flight.abort_all();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::peer;
    use crate::peer::extension::{DontHaveExtension, MetadataExtension};
    use crate::peer::{ConnectionProtocol, MockDiscovery, PeerDiscovery};
    use std::net::Ipv4Addr;
    use tempfile::tempdir;
    use tokio::time;

    #[tokio::test]
    async fn test_execute() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        let uri = "magnet:?xt=urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7&dn=debian-12.4.0-amd64-DVD-1.iso&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451%2Fannounce&tr=udp%3A%2F%2Ftracker.bittor.pw%3A1337%2Fannounce&tr=udp%3A%2F%2Fpublic.popcorn-tracker.org%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce";
        let (mut context, _) = torrent_context!(
            uri,
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![]
        );
        let mut operation = ConnectPeersOperation::new(true);

        let result = operation.execute(&mut context, vec![].as_slice()).await;

        assert_eq!(TorrentOperationResult::Continue, result);
    }

    #[tokio::test]
    async fn test_update_max_in_flight() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        let uri = "magnet:?xt=urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7&dn=debian-12.4.0-amd64-DVD-1.iso&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451%2Fannounce&tr=udp%3A%2F%2Ftracker.bittor.pw%3A1337%2Fannounce&tr=udp%3A%2F%2Fpublic.popcorn-tracker.org%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce";
        let (context, _) = torrent_context!(
            uri,
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().peers_in_flight(35).build(),
            vec![]
        );
        let mut operation = ConnectPeersOperation::new(true);

        // update the permits from the torrent settings
        operation.update_max_in_flight(&context);

        assert_eq!(
            35, operation.max_in_flight,
            "expected the max in flight to have been updated"
        );
    }

    #[tokio::test]
    async fn test_burst() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        let uri = "magnet:?xt=urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7&dn=debian-12.4.0-amd64-DVD-1.iso&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451%2Fannounce&tr=udp%3A%2F%2Ftracker.bittor.pw%3A1337%2Fannounce&tr=udp%3A%2F%2Fpublic.popcorn-tracker.org%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce";
        let (context, _) = torrent_context!(
            uri,
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder()
                .peers_in_flight(20)
                .peers_upper_limit(200)
                .build(),
            vec![]
        );
        let mut operation = ConnectPeersOperation::new(true);

        // update the permits from the torrent settings
        operation.update_max_in_flight(&context);
        let result = operation.max_in_flight;
        assert_eq!(20, result);

        // invoke the burst fn
        operation.burst(&context);
        assert_eq!(
            200, operation.max_in_flight,
            "expected the max in flight to have been temporary bursted"
        );
        assert_ne!(
            None, operation.bursting_since,
            "expected the bursting since to be set"
        );
    }

    #[tokio::test]
    async fn test_peer_connection_failed() {
        init_logger!();
        let temp_dir = tempdir().unwrap();
        let temp_path = temp_dir.path().to_str().unwrap();
        let mut dialer = MockDiscovery::new();
        dialer
            .expect_dial()
            .returning(|_, _, _, _, _, _, _, _, _, _, _| {
                Err(peer::Error::Io(io::Error::new(
                    io::ErrorKind::TimedOut,
                    "timeout",
                )))
            });
        dialer
            .expect_protocol()
            .return_const(ConnectionProtocol::Tcp);
        let dialers: Vec<PeerDiscovery> = vec![dialer.into()];
        let (mut context, mut receiver) = torrent_context!(
            "debian.torrent",
            temp_path,
            TorrentFlags::none(),
            TorrentConfig::builder().build(),
            vec![],
            vec![|| MetadataExtension::new().into(), || {
                DontHaveExtension::new().into()
            },],
            None
        );
        let mut operation = ConnectPeersOperation::new(false);

        // add an invalid peer address
        let addr = SocketAddr::from((Ipv4Addr::LOCALHOST, 13470));
        context.peer_pool_mut().add_peer_addresses(vec![addr], None);

        // execute the operation
        let result = operation.execute(&mut context, dialers.as_slice()).await;
        assert_eq!(TorrentOperationResult::Continue, result);

        // wait for the in_flight operation to complete
        timeout!(
            Duration::from_secs(1),
            async {
                loop {
                    operation.poll_in_flight(&context);
                    if operation.in_flight.is_empty() {
                        break;
                    }
                    time::sleep(Duration::from_millis(5)).await;
                }
            },
            "expected the in flight operation to complete"
        );

        let command = timeout!(Duration::from_millis(250), receiver.recv())
            .expect("expected a command to have been sent");
        match command {
            TorrentCommand::PeerClosed { reason, .. } => {
                assert_eq!(CloseReason::Timeout, reason);
            }
            _ => assert!(
                false,
                "expected TorrentCommand::PeerClosed, but got {:?}",
                command
            ),
        }
    }

    mod initialize {
        use super::*;

        #[tokio::test]
        async fn test_holepunch_supported() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let (mut context, _receiver) = torrent_context!(
                "debian.torrent",
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![],
                vec![|| HolepunchExtension::new().into()],
                None,
                None
            );
            let mut operation = ConnectPeersOperation::new(false);

            // execute the operation
            let dialers = vec![];
            let result = operation.execute(&mut context, dialers.as_slice()).await;
            assert_eq!(TorrentOperationResult::Continue, result);
            assert_eq!(
                true, operation.initialized,
                "expected the operation to have been initialized"
            );

            // check that the hole punch support is enabled
            assert_eq!(
                true, operation.holepunch_supported,
                "expected hole punch support to be enabled"
            );
        }

        #[tokio::test]
        async fn test_holepunch_unsupported() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let (mut context, _receiver) = torrent_context!(
                "debian.torrent",
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![],
                vec![],
                None,
                None
            );
            let mut operation = ConnectPeersOperation::new(false);

            // execute the operation
            let dialers = vec![];
            let result = operation.execute(&mut context, dialers.as_slice()).await;
            assert_eq!(TorrentOperationResult::Continue, result);
            assert_eq!(
                true, operation.initialized,
                "expected the operation to have been initialized"
            );

            // check the hole punch support of the torrent
            assert_eq!(
                false, operation.holepunch_supported,
                "expected hole punch to not have been supported"
            );
        }
    }

    mod webseed_url {
        use super::*;

        #[tokio::test]
        async fn test_create_webseed_urls() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let expected_url = Url::parse("https://archive.org/download/").unwrap();
            let uri = "magnet:?xt=urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7&dn=debian-12.4.0-amd64-DVD-1.iso&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451%2Fannounce&tr=udp%3A%2F%2Ftracker.bittor.pw%3A1337%2Fannounce&tr=udp%3A%2F%2Fpublic.popcorn-tracker.org%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce&ws=https%3A%2F%2Farchive.org%2Fdownload%2F";
            let (context, _) = torrent_context!(
                uri,
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().build(),
                vec![],
                vec![],
                None
            );
            let mut operation = ConnectPeersOperation::new(true);

            operation.create_webseed_urls(&context);

            assert_eq!(1, operation.webseeds.len());
            assert_eq!(expected_url, operation.webseeds.values().next().unwrap()[0]);
        }

        #[tokio::test]
        async fn test_create_webseed_peers() {
            init_logger!();
            let temp_dir = tempdir().unwrap();
            let temp_path = temp_dir.path().to_str().unwrap();
            let uri = "magnet:?xt=urn:btih:EADAF0EFEA39406914414D359E0EA16416409BD7&dn=debian-12.4.0-amd64-DVD-1.iso&tr=udp%3A%2F%2Ftracker.opentrackr.org%3A1337&tr=udp%3A%2F%2Fopen.stealth.si%3A80%2Fannounce&tr=udp%3A%2F%2Ftracker.torrent.eu.org%3A451%2Fannounce&tr=udp%3A%2F%2Ftracker.bittor.pw%3A1337%2Fannounce&tr=udp%3A%2F%2Fpublic.popcorn-tracker.org%3A6969%2Fannounce&tr=udp%3A%2F%2Ftracker.dler.org%3A6969%2Fannounce&tr=udp%3A%2F%2Fexodus.desync.com%3A6969&tr=udp%3A%2F%2Fopen.demonii.com%3A1337%2Fannounce&ws=https%3A%2F%2Farchive.org%2Fdownload%2F";
            let (context, _) = torrent_context!(
                uri,
                temp_path,
                TorrentFlags::none(),
                TorrentConfig::builder().peers_in_flight(50).build(),
                vec![],
                vec![],
                None
            );
            let mut operation = ConnectPeersOperation::new(true);

            // set the webseed urls
            operation.webseeds = vec![
                (
                    SocketAddr::from((Ipv4Addr::LOCALHOST, 80)),
                    vec![Url::parse("https://test-url-1.com/").unwrap()],
                ),
                (
                    SocketAddr::from((Ipv4Addr::LOCALHOST, 443)),
                    vec![Url::parse("https://test-url-2.com/").unwrap()],
                ),
            ]
            .into_iter()
            .collect();

            // update the max in-flight
            operation.update_max_in_flight(&context);

            // create new webseed peers
            let mut wanted_connections = 100;
            operation.create_webseed_peers(&mut wanted_connections, &context);
            assert_eq!(
                98, wanted_connections,
                "expected 98 remaining connections to be wanted"
            );
            assert_eq!(
                0,
                operation.webseeds.len(),
                "expected the webseed urls to be consumed"
            );
        }
    }
}