aria2-core 0.3.2

aria2-rust core download engine: multi-protocol segmented downloads, rate limiting, configuration, session persistence, and BitTorrent seeding
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
//! Unified tracker announce dispatcher integrating BtAnnounce state machine
//! with both HTTP and UDP tracker backends.
//!
//! # C++ Reference
//!
//! In C++ aria2, `DefaultBtAnnounce` creates either an `HttpRequestCommand`
//! or a `UDPTrackerRequest` depending on the tracker URL scheme. The dispatch
//! happens inside `DefaultBtAnnounce::getAnnounceUrl()` (HTTP) and
//! `DefaultBtAnnounce::createUDPTrackerRequest()` (UDP).
//!
//! This module unifies both paths through a single `TrackerAnnouncer` that
//! uses the `BtAnnounce` state machine to decide *when* and *what* to
//! announce, then routes to the correct backend based on URL scheme.

use std::collections::HashSet;
use std::sync::Arc;
use std::time::Duration;
use tracing::{debug, info, warn};

use super::bt_announce::{BtAnnounce, is_udp_tracker};
use super::types::AnnounceEvent;
use crate::engine::udp_tracker_client::SharedUdpClient;
use crate::engine::udp_tracker_manager::UdpTrackerManager;
use crate::http::client_identity::ClientTlsConfig;
use aria2_protocol::bittorrent::tracker::public_list::{PublicTrackerList, TrackerFailureKind};
use aria2_protocol::bittorrent::tracker::udp_tracker_protocol::UdpError;

/// Result of a tracker announce operation (HTTP or UDP).
#[derive(Debug, Clone)]
pub struct AnnounceResult {
    /// Peer addresses discovered from the tracker.
    pub peers: Vec<(String, u16)>,
    /// Recommended announce interval from the tracker response.
    pub interval: Duration,
    /// Number of seeders reported by the tracker.
    pub seeders: i64,
    /// Number of leechers reported by the tracker.
    pub leechers: i64,
    /// The announce event that was sent.
    pub event: AnnounceEvent,
    /// The tracker URL that was used for this announce.
    pub tracker_url: String,
}

/// Unified tracker announcer that dispatches HTTP and UDP tracker announces
/// through the `BtAnnounce` state machine.
///
/// This replaces the ad-hoc UDP tracker usage in `discover_peers()` with
/// a proper state-machine-driven approach that:
/// - Uses `BtAnnounce::adjust_announce_list()` to determine event and timing
/// - Routes HTTP URLs through the existing HTTP announce path
/// - Routes UDP URLs through `UdpTrackerManager`
/// - Processes responses through `BtAnnounce::process_*_response()`
/// - Tracks announce success/failure for tier rotation
pub struct TrackerAnnouncer {
    /// The core announce state machine.
    announce: BtAnnounce,
    /// Prevent duplicate stopped events after a successful announce.
    stopped_sent: bool,
    /// UDP tracker manager (created lazily when first UDP URL is seen).
    udp_manager: Option<UdpTrackerManager>,
    /// Shared UDP client for the UDP tracker manager.
    udp_client: Option<SharedUdpClient>,
    /// URL selected for the most recent announce attempt, including failures.
    last_attempt_tracker_url: Option<String>,
    /// Shared process-wide catalog for public tracker health feedback.
    public_tracker_catalog: Option<Arc<PublicTrackerList>>,
    /// Public URLs appended to this command's announce list.
    public_tracker_urls: HashSet<String>,
    /// Failure classification from the most recent announce attempt.
    last_failure_kind: Option<TrackerFailureKind>,
    /// Existing download TLS settings used by HTTPS tracker announces.
    http_tls: ClientTlsConfig,
    /// Per-download tracker request timeout.
    tracker_timeout_secs: u64,
    /// Per-download tracker connection timeout.
    tracker_connect_timeout_secs: u64,
}

impl TrackerAnnouncer {
    /// Create a new tracker announcer from an announce list and optional single URL.
    pub fn new(announce_list: &[Vec<String>], announce: &Option<String>) -> Self {
        Self {
            announce: BtAnnounce::new(announce_list, announce),
            stopped_sent: false,
            udp_manager: None,
            udp_client: None,
            last_attempt_tracker_url: None,
            public_tracker_catalog: None,
            public_tracker_urls: HashSet::new(),
            last_failure_kind: None,
            http_tls: ClientTlsConfig::default(),
            tracker_timeout_secs: 60,
            tracker_connect_timeout_secs: 60,
        }
    }

    /// Create from an existing `BtAnnounce` and optional shared UDP client.
    pub fn with_udp_client(announce: BtAnnounce, udp_client: Option<SharedUdpClient>) -> Self {
        Self {
            announce,
            stopped_sent: false,
            udp_manager: None,
            udp_client,
            last_attempt_tracker_url: None,
            public_tracker_catalog: None,
            public_tracker_urls: HashSet::new(),
            last_failure_kind: None,
            http_tls: ClientTlsConfig::default(),
            tracker_timeout_secs: 60,
            tracker_connect_timeout_secs: 60,
        }
    }

    /// Set the shared UDP client for UDP tracker announces.
    pub fn set_udp_client(&mut self, client: SharedUdpClient) {
        self.udp_client = Some(client);
    }

    /// Apply the existing aria2-compatible TLS options to HTTP tracker calls.
    pub(crate) fn set_http_tls_config(&mut self, config: ClientTlsConfig) {
        self.http_tls = config;
    }

    /// Set the per-download tracker request and connection timeouts.
    pub fn set_timeouts(&mut self, request: Duration, connect: Duration) {
        self.tracker_timeout_secs = request.as_secs().max(1);
        self.tracker_connect_timeout_secs = connect.as_secs().max(1);
    }

    /// Apply the user-defined announce interval from `bt-tracker-interval`.
    pub fn set_user_defined_interval(&mut self, interval: Duration) {
        self.announce.set_user_defined_interval(interval);
    }

    /// Apply the announce encryption and external-IP options.
    pub fn set_announce_options(&mut self, force_encryption: bool, external_ip: Option<String>) {
        self.announce.set_force_encryption(force_encryption);
        self.announce.set_external_ip(external_ip);
    }

    /// Returns true if any announce is ready (stopped, completed, or periodic).
    pub fn is_announce_ready(&self) -> bool {
        self.announce.is_announce_ready()
    }

    /// Returns true if a periodic announce is ready.
    pub fn is_default_announce_ready(&self) -> bool {
        self.announce.is_default_announce_ready()
    }

    /// Return the delay until the next protocol-defined periodic announce.
    pub fn next_default_announce_delay(&self) -> Option<std::time::Duration> {
        self.announce.next_default_announce_delay()
    }

    /// Return the tracker selected for the next announce attempt.
    pub fn current_tracker_url(&self) -> Option<&str> {
        self.announce.announce_list().get_announce()
    }

    /// Return the URL used by the most recent announce attempt.
    pub fn last_attempt_tracker_url(&self) -> Option<&str> {
        self.last_attempt_tracker_url.as_deref()
    }

    /// Attach the shared catalog and the public URLs owned by this command.
    pub fn set_public_tracker_catalog(
        &mut self,
        catalog: Arc<PublicTrackerList>,
        public_tracker_urls: HashSet<String>,
    ) {
        self.public_tracker_catalog = Some(catalog);
        self.public_tracker_urls = public_tracker_urls;
    }

    /// Execute a tracker announce, dispatching to HTTP or UDP as appropriate.
    ///
    /// This is the main entry point called from the download loop. It:
    /// 1. Checks if an announce is ready via the state machine
    /// 2. Determines the current tracker URL and event
    /// 3. Dispatches to the appropriate backend
    /// 4. Processes the response through the state machine
    /// 5. Returns the result with discovered peers
    ///
    /// Returns `None` if no announce is ready or the state machine decides
    /// not to announce (e.g., all tiers failed).
    pub async fn announce(
        &mut self,
        info_hash: &[u8; 20],
        peer_id: &[u8; 20],
        downloaded: u64,
        left: u64,
        uploaded: u64,
    ) -> Option<AnnounceResult> {
        // Check if announce is ready
        if !self.announce.is_announce_ready() {
            return None;
        }
        if !self.announce.adjust_announce_list() {
            return None;
        }

        let tracker_url = self.announce.announce_list().get_announce()?.to_string();
        self.last_attempt_tracker_url = Some(tracker_url.clone());
        self.last_failure_kind = None;
        let is_udp = is_udp_tracker(&tracker_url);
        let event = self.announce.announce_list().get_event();

        // Determine if this is a UDP or HTTP tracker
        let result = if is_udp {
            self.announce_udp(info_hash, peer_id, downloaded, left, uploaded, &tracker_url)
                .await
        } else {
            // HTTP announce — build URL and dispatch
            self.announce_http(
                info_hash,
                peer_id,
                downloaded,
                left,
                uploaded,
                event,
                &tracker_url,
            )
            .await
        };

        if self.public_tracker_urls.contains(&tracker_url)
            && let Some(catalog) = self.public_tracker_catalog.as_ref()
        {
            if result.is_some() {
                catalog.record_success(&tracker_url).await;
            } else {
                catalog
                    .record_failure_kind(
                        &tracker_url,
                        self.last_failure_kind
                            .unwrap_or(TrackerFailureKind::MalformedResponse),
                    )
                    .await;
            }
        }
        result
    }

    /// Execute a UDP tracker announce.
    async fn announce_udp(
        &mut self,
        info_hash: &[u8; 20],
        peer_id: &[u8; 20],
        downloaded: u64,
        left: u64,
        uploaded: u64,
        tracker_url: &str, // must be &str for lifetime flexibility
    ) -> Option<AnnounceResult> {
        let event = self.announce.announce_list().get_event();
        let udp_event = self.announce.current_udp_event();
        let numwant = self.announce.numwant();
        // Initialize UDP manager lazily
        if self.udp_manager.is_none() {
            if let Some(ref client) = self.udp_client {
                let mgr = UdpTrackerManager::new(Arc::clone(client)).await;
                self.udp_manager = Some(mgr);
            } else {
                // No UDP client configured — try to create one
                match crate::engine::udp_tracker_client::UdpTrackerClient::new(0).await {
                    Ok(client) => {
                        let shared = Arc::new(tokio::sync::Mutex::new(client));
                        self.udp_client = Some(Arc::clone(&shared));
                        let mgr = UdpTrackerManager::new(shared).await;
                        self.udp_manager = Some(mgr);
                    }
                    Err(e) => {
                        warn!("[BT] Failed to create UDP tracker client: {}", e);
                        self.last_failure_kind = Some(TrackerFailureKind::Network);
                        self.announce.announce_failure();
                        return None;
                    }
                }
            }
        }

        let mgr = self.udp_manager.as_mut()?;
        mgr.set_request_timeout(Duration::from_secs(self.tracker_timeout_secs));

        // The state machine selects one URL per attempt. Keep the UDP manager
        // scoped to that URL so responses cannot be attributed to a different
        // public tracker accumulated by an earlier attempt.
        mgr.use_tracker_url(tracker_url).await;

        // Signal announce start
        self.announce.announce_start();

        // The event and numwant were captured before network I/O so the
        // request and result describe the same state-machine transition.

        debug!(
            "[BT] Announcing to UDP tracker {} (event={:?}, udp_event={})",
            tracker_url, event, udp_event
        );

        let responses = mgr
            .announce(
                info_hash,
                peer_id,
                downloaded as i64,
                left as i64,
                uploaded as i64,
                udp_event,
                numwant as i32,
            )
            .await;

        if responses.is_empty() {
            warn!("[BT] UDP tracker {} returned no response", tracker_url);
            self.last_failure_kind = Some(match mgr.last_announce_error().await {
                Some(UdpError::TrackerError) => TrackerFailureKind::TrackerRejected,
                Some(UdpError::MalformedResponse) => TrackerFailureKind::MalformedResponse,
                Some(UdpError::Network) => TrackerFailureKind::Network,
                Some(UdpError::Timeout) | None => TrackerFailureKind::Timeout,
                Some(UdpError::Success | UdpError::Shutdown) => {
                    TrackerFailureKind::MalformedResponse
                }
            });
            self.announce.announce_failure();
            return None;
        }

        // Process the first response through the state machine
        let response = &responses[0];
        let peers = self.announce.process_udp_announce_response(response);
        self.announce.announce_success();

        // Collect additional peers from subsequent responses
        let mut all_peers = peers;
        if responses.len() > 1 {
            for resp in &responses[1..] {
                all_peers.extend_from_slice(&resp.peers);
            }
        }

        // Deduplicate peers
        all_peers.sort_by(|a, b| a.0.cmp(&b.0).then(a.1.cmp(&b.1)));
        all_peers.dedup();

        Some(AnnounceResult {
            peers: all_peers,
            interval: self.announce.interval(),
            seeders: self.announce.complete(),
            leechers: self.announce.incomplete(),
            event,
            tracker_url: tracker_url.to_string(),
        })
    }

    /// Execute an HTTP tracker announce.
    #[allow(clippy::too_many_arguments)]
    async fn announce_http(
        &mut self,
        info_hash: &[u8; 20],
        peer_id: &[u8; 20],
        downloaded: u64,
        left: u64,
        uploaded: u64,
        event: AnnounceEvent,
        tracker_url: &str,
    ) -> Option<AnnounceResult> {
        // Build the announce URL through BtAnnounce state machine
        let url = self.announce.get_announce_url_without_adjustment(
            info_hash, peer_id, uploaded, downloaded, left, None,
        )?;

        // Signal announce start
        self.announce.announce_start();

        debug!(
            "[BT] Announcing to HTTP tracker {} (event={:?})",
            tracker_url, event
        );

        // Send HTTP request
        match crate::engine::http_tracker_client::build_tracker_client_with_tls_and_timeouts(
            self.tracker_timeout_secs,
            self.tracker_connect_timeout_secs,
            &self.http_tls,
        ) {
            Ok(client) => {
                match client.get(&url).send().await {
                    Ok(resp) => {
                        if !resp.status().is_success() {
                            warn!(
                                "[BT] HTTP tracker {} returned status {}",
                                tracker_url,
                                resp.status()
                            );
                            self.last_failure_kind = Some(
                                if resp.status().is_server_error()
                                    || matches!(resp.status().as_u16(), 408 | 425 | 429)
                                {
                                    TrackerFailureKind::RemoteTemporary
                                } else {
                                    TrackerFailureKind::TrackerRejected
                                },
                            );
                            self.announce.announce_failure();
                            return None;
                        }

                        match resp.bytes().await {
                            Ok(body) => {
                                match aria2_protocol::bittorrent::tracker::response::TrackerResponse::parse(&body) {
                                    Ok(tracker_resp) => {
                                        if tracker_resp.is_failure() {
                                            let reason = tracker_resp.failure_reason
                                                .unwrap_or_else(|| "tracker failure".to_string());
                                            warn!("[BT] HTTP tracker {} failure: {}", tracker_url, reason);
                                            self.last_failure_kind =
                                                Some(TrackerFailureKind::TrackerRejected);
                                            self.announce.announce_failure();
                                            return None;
                                        }

                                        // Process through BtAnnounce state machine
                                        match self.announce.process_announce_response(&tracker_resp) {
                                            Ok(peers) => {
                                                self.announce.announce_success();
                                                let interval = self.announce.interval();
                                                let seeders = self.announce.complete();
                                                let leechers = self.announce.incomplete();
                                                Some(AnnounceResult {
                                                    peers,
                                                    interval,
                                                    seeders,
                                                    leechers,
                                                    event,
                                                    tracker_url: tracker_url.to_string(),
                                                })
                                            }
                                            Err(e) => {
                                                warn!(
                                                    "[BT] HTTP tracker {} response processing failed: {}",
                                                    tracker_url, e
                                                );
                                                self.last_failure_kind =
                                                    Some(TrackerFailureKind::MalformedResponse);
                                                self.announce.announce_failure();
                                                None
                                            }
                                        }
                                    }
                                    Err(e) => {
                                        warn!(
                                            "[BT] HTTP tracker {} response parse failed: {}",
                                            tracker_url, e
                                        );
                                        self.last_failure_kind =
                                            Some(TrackerFailureKind::MalformedResponse);
                                        self.announce.announce_failure();
                                        None
                                    }
                                }
                            }
                            Err(e) => {
                                warn!("[BT] HTTP tracker {} body read failed: {}", tracker_url, e);
                                self.last_failure_kind = Some(if e.is_timeout() {
                                    TrackerFailureKind::Timeout
                                } else {
                                    TrackerFailureKind::Network
                                });
                                self.announce.announce_failure();
                                None
                            }
                        }
                    }
                    Err(e) => {
                        warn!("[BT] HTTP tracker {} request failed: {}", tracker_url, e);
                        self.last_failure_kind = Some(if e.is_timeout() {
                            TrackerFailureKind::Timeout
                        } else {
                            TrackerFailureKind::Network
                        });
                        self.announce.announce_failure();
                        None
                    }
                }
            }
            Err(e) => {
                warn!(
                    "[BT] Failed to build HTTP tracker client for {}: {}",
                    tracker_url, e
                );
                self.last_failure_kind = Some(TrackerFailureKind::Network);
                self.announce.announce_failure();
                None
            }
        }
    }

    /// Send a "stopped" event to all trackers before shutdown.
    ///
    /// C++ aria2 sends stopped events during `DownloadEngine::setHaltRequested()`.
    /// This should be called before the download command exits.
    pub async fn announce_stopped(
        &mut self,
        info_hash: &[u8; 20],
        peer_id: &[u8; 20],
        downloaded: u64,
        left: u64,
        uploaded: u64,
    ) {
        if self.stopped_sent {
            return;
        }
        self.announce.set_runtime_halted(true);

        // Try to send stopped event to all applicable tiers
        let mut attempts = 0;
        const MAX_STOPPED_ATTEMPTS: usize = 5;
        let mut sent_successfully = false;

        while self.announce.is_stopped_announce_ready() && attempts < MAX_STOPPED_ATTEMPTS {
            if let Some(result) = self
                .announce(info_hash, peer_id, downloaded, left, uploaded)
                .await
            {
                info!(
                    "[BT] Sent stopped event to {} ({} peers in response)",
                    result.tracker_url,
                    result.peers.len()
                );
                sent_successfully = true;
            }
            attempts += 1;
        }
        self.stopped_sent = sent_successfully;
    }

    /// Send a "completed" event to all applicable trackers.
    ///
    /// Called when the download finishes all pieces.
    pub async fn announce_completed(
        &mut self,
        info_hash: &[u8; 20],
        peer_id: &[u8; 20],
        downloaded: u64,
        uploaded: u64,
    ) {
        self.announce.set_download_complete(true);

        if let Some(result) = self
            .announce(info_hash, peer_id, downloaded, 0, uploaded)
            .await
        {
            info!(
                "[BT] Sent completed event to {} ({} seeders, {} leechers)",
                result.tracker_url, result.seeders, result.leechers
            );
        }
    }

    /// Get the current announce interval.
    pub fn interval(&self) -> Duration {
        self.announce.interval()
    }

    /// Get the current minimum interval.
    pub fn min_interval(&self) -> Duration {
        self.announce.min_interval()
    }

    /// Get access to the inner BtAnnounce for advanced state queries.
    pub fn bt_announce(&self) -> &BtAnnounce {
        &self.announce
    }

    /// Get mutable access to the inner BtAnnounce for state updates.
    pub fn bt_announce_mut(&mut self) -> &mut BtAnnounce {
        &mut self.announce
    }

    /// Check if all tracker tiers have failed.
    pub fn is_all_announce_failed(&self) -> bool {
        self.announce.is_all_announce_failed()
    }

    /// Reset the announce state (e.g., after a long pause).
    pub fn reset_announce(&mut self) {
        self.announce.reset_announce();
    }

    /// Set whether the download has fewer than minimum peers.
    pub fn set_less_than_min_peers(&mut self, less: bool) {
        self.announce.set_less_than_min_peers(less);
    }

    /// Set the TCP port for announce URL construction.
    pub fn set_tcp_port(&mut self, port: u16) {
        self.announce.set_tcp_port(port);
    }

    /// Return the TCP port currently advertised to trackers.
    pub fn tcp_port(&self) -> u16 {
        self.announce.tcp_port()
    }

    /// Set whether the download is complete.
    pub fn set_download_complete(&mut self, complete: bool) {
        self.announce.set_download_complete(complete);
    }

    /// Set whether the runtime is halted (stopping).
    pub fn set_runtime_halted(&mut self, halted: bool) {
        self.announce.set_runtime_halted(halted);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn tracker_timeout_options_are_stored_for_both_transports() {
        let mut announcer = TrackerAnnouncer::new(
            &[vec!["http://tracker.example.com/announce".to_string()]],
            &None,
        );
        announcer.set_timeouts(Duration::from_secs(7), Duration::from_secs(11));

        assert_eq!(announcer.tracker_timeout_secs, 7);
        assert_eq!(announcer.tracker_connect_timeout_secs, 11);
    }

    #[tokio::test]
    async fn tracker_request_timeout_aborts_a_slow_http_announce() {
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0")
            .await
            .expect("bind local tracker test listener");
        let address = listener.local_addr().expect("local tracker address");
        let server = tokio::spawn(async move {
            let (mut socket, _) = listener.accept().await.expect("accept tracker request");
            tokio::time::sleep(Duration::from_secs(2)).await;
            use tokio::io::AsyncWriteExt;
            let _ = socket
                .write_all(b"HTTP/1.1 200 OK\r\nContent-Length: 0\r\n\r\n")
                .await;
        });

        let url = format!("http://{address}/announce");
        let mut announcer = TrackerAnnouncer::new(&[vec![url]], &None);
        announcer.set_timeouts(Duration::from_secs(1), Duration::from_secs(1));

        let result = tokio::time::timeout(
            Duration::from_secs(4),
            announcer.announce(&[0u8; 20], &[1u8; 20], 0, 1, 0),
        )
        .await
        .expect("tracker request should finish within the test deadline");
        assert!(result.is_none(), "slow tracker request should time out");

        server.await.expect("tracker test server should exit");
    }

    #[test]
    fn test_tracker_announcer_creation() {
        let announcer = TrackerAnnouncer::new(&[], &None);
        assert!(!announcer.is_announce_ready());
        assert!(announcer.is_all_announce_failed());
    }

    #[test]
    fn test_tracker_announcer_with_announce_url() {
        let urls = vec![vec!["http://tracker.example.com:6969/announce".to_string()]];
        let announcer = TrackerAnnouncer::new(&urls, &None);
        // Announce should be ready initially (no prev_announce_time)
        assert!(announcer.is_announce_ready());
    }

    #[test]
    fn test_tracker_announcer_udp_detection() {
        let urls = vec![vec!["udp://tracker.example.com:6969/announce".to_string()]];
        let _announcer = TrackerAnnouncer::new(&urls, &None);
        // BtAnnounce should detect the UDP URL
        assert!(is_udp_tracker("udp://tracker.example.com:6969/announce"));
        assert!(!is_udp_tracker("http://tracker.example.com:6969/announce"));
    }

    #[test]
    fn test_announce_result_fields() {
        let result = AnnounceResult {
            peers: vec![("10.0.0.1".to_string(), 6881)],
            interval: Duration::from_secs(300),
            seeders: 5,
            leechers: 10,
            event: AnnounceEvent::Started,
            tracker_url: "udp://tracker.example.com:6969/announce".to_string(),
        };
        assert_eq!(result.peers.len(), 1);
        assert_eq!(result.seeders, 5);
        assert_eq!(result.leechers, 10);
    }
}