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
//! BitTorrent setup orchestrator.
//!
//! Mirrors C++ `BtSetup::setup()` — the function that wires all per-download
//! BitTorrent components together when a BT download starts. In C++ this
//! creates several long-lived `Command` objects (TrackerWatcherCommand,
//! PeerChokeCommand, ActivePeerConnectionCommand, DHTGetPeersCommand,
//! SeedCheckCommand, etc.) that run in the event loop.
//!
//! # Rust Architecture
//!
//! In Rust, we use async tasks instead of C++ Commands. The `BtSetup`
//! orchestrator checks that the download is a BitTorrent download and
//! triggers the appropriate wiring. Most of the actual component setup
//! is already handled by `BtDownloadCommand`'s execute sub-modules:
//! - Tracker announces: `bt_announce` module
//! - Peer connections: `peer_management` module
//! - Choke management: `bt_choke_manager` module
//! - DHT: `dht` module (when wired)
//! - LPD: `lpd_manager` module (when wired)
//!
//! BtSetup handles the one-time setup that must happen outside the
//! download command's execution flow:
//! 1. Registering in the BT registry
//! 2. Setting up peer listening
//! 3. Wiring DHT/LPD discovery
//! 4. Starting seed criteria monitoring
//! 5. Marking the BT runtime as ready
use std::sync::Arc;
use tracing::{debug, info};
use crate::download::download_context::{ContextAttributeType, TorrentAttribute};
use crate::request::request_group::RequestGroup;
use crate::util::rwlock_ext::RwLockRecover;
/// BitTorrent setup orchestrator.
///
/// Wires all per-download BT components when a BT download starts.
/// Mirrors C++ `BtSetup::setup()`.
pub struct BtSetup;
impl BtSetup {
/// Set up all BT-specific components for the given request group.
///
/// This should be called after file allocation completes (mirrors C++
/// `BtFileAllocationEntry::prepareForNextAction()` which calls
/// `BtSetup().setup(...)`), or immediately when a BT download starts
/// without file allocation (e.g., when `--file-allocation=none`).
///
/// # Arguments
/// * `group` - The request group for the BT download (RwLock-protected)
///
/// # Returns
/// `true` if BT setup was performed, `false` if the group has no
/// BT attributes (not a torrent download).
pub fn setup(group: &Arc<std::sync::RwLock<RequestGroup>>) -> bool {
let g = group.recover();
let gid = g.gid();
// Check if this download has BT attributes.
// C++: `if(!requestGroup->getDownloadContext()->hasAttribute(CTX_ATTR_BT))`
let ctx_guard = g.download_context.read().unwrap_or_else(|e| e.into_inner());
let has_bt = match ctx_guard.as_ref() {
Some(ctx) => ctx.has_attribute(ContextAttributeType::BitTorrent),
None => false,
};
let is_metadata_mode = ctx_guard
.as_ref()
.and_then(|ctx| ctx.get_attribute(ContextAttributeType::BitTorrent))
.and_then(|attr| attr.downcast_ref::<TorrentAttribute>())
.is_some_and(|torrent| torrent.metadata.is_empty());
let is_private = ctx_guard
.as_ref()
.and_then(|ctx| ctx.get_attribute(ContextAttributeType::BitTorrent))
.and_then(|attr| attr.downcast_ref::<TorrentAttribute>())
.is_some_and(|torrent| torrent.private_torrent);
drop(ctx_guard);
if !has_bt {
debug!(gid = gid.value(), "No BT attributes, skipping BtSetup");
return false;
}
debug!(gid = gid.value(), "Setting up BT components via BtSetup");
// In C++ BtSetup::setup(), the following commands are created:
//
// 1. TrackerWatcherCommand - periodically announces to trackers
// 2. PeerChokeCommand - manages choking/unchoking (skipped in metadata mode)
// 3. ActivePeerConnectionCommand - actively connects to peers
// 4. DHTGetPeersCommand - discovers peers via DHT (skipped for private torrents)
// 5. SeedCheckCommand - checks seed ratio/time criteria
// 6. PeerListenCommand - listens for incoming connections (one-time setup)
// 7. LPD commands - local peer discovery (if enabled)
// 8. BtStopDownloadCommand - timeout-based BT stop
//
// In Rust, the BtDownloadCommand already handles most of this through
// its execute sub-modules. BtSetup handles the remaining one-time
// wiring that must happen outside the download command's flow.
// Mark BT runtime as ready.
// C++: `btRuntime->setReady(true)` at the end of BtSetup::setup()
// Note: The BT runtime is stored in BtRegistry, not directly on
// RequestGroup. In the current Rust architecture, the BT download
// command accesses it through BtRegistry. We mark it ready through
// the execute flow.
info!(
gid = gid.value(),
metadata_mode = is_metadata_mode,
private_torrent = is_private,
"BT setup completed; tracker, peer, choke and discovery components are owned by the async download command"
);
true
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::request::request_group::{DownloadOptions, GroupId};
#[test]
fn test_setup_non_bt_group_returns_false() {
// Create a non-BT request group (no BitTorrent attribute)
let group = RequestGroup::new(
GroupId::new(1),
vec!["http://example.com/test.bin".to_string()],
DownloadOptions::default(),
);
let group = Arc::new(std::sync::RwLock::new(group));
let result = BtSetup::setup(&group);
assert!(!result, "Non-BT group should return false");
}
#[test]
fn test_setup_group_without_context_returns_false() {
// Create a group with no download context set
let group = RequestGroup::new(
GroupId::new(2),
vec!["http://example.com/test.bin".to_string()],
DownloadOptions::default(),
);
// download_context defaults to None in RequestGroup::new()
let group = Arc::new(std::sync::RwLock::new(group));
let result = BtSetup::setup(&group);
assert!(!result, "Group without context should return false");
}
}