pub mod types;
pub use types::{BAD_DATA_THRESHOLD, SeedExitCondition, UploadSession};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
use tracing::{debug, info, warn};
use crate::engine::bt_choke_manager::BtSeederStateChoke;
use crate::engine::bt_piece_downloader::FileBackedPieceProvider;
use crate::engine::bt_tracker_comm::TrackerAnnouncer;
use crate::engine::bt_upload_session::{BtSeedingConfig, BtUploadSession, PieceDataProvider};
use crate::engine::choking_algorithm::ChokingAlgorithm;
use crate::engine::peer_stats::PeerStats;
const SEED_TICK_INTERVAL: Duration = Duration::from_secs(2);
const MSG_READ_TIMEOUT: Duration = Duration::from_millis(200);
const CHOKE_ROUND_INTERVAL_SECS: u64 = 10;
pub struct BtSeedManager {
info_hash: [u8; 20],
upload_sessions: Vec<BtUploadSession>,
peer_stats: Vec<PeerStats>,
piece_provider: Option<Arc<dyn PieceDataProvider>>,
#[allow(dead_code)]
config: BtSeedingConfig,
exit_condition: SeedExitCondition,
total_downloaded: u64,
pub total_uploaded: u64,
pub seeding_start_time: Instant,
is_active: bool,
seeder_choke: BtSeederStateChoke,
#[allow(dead_code)]
choking_algo: Option<ChokingAlgorithm>,
cancel_token: CancellationToken,
peer_storage: Option<
std::sync::Arc<std::sync::Mutex<crate::engine::bt_peer_storage::DefaultPeerStorage>>,
>,
halt_requested: bool,
last_choke_time: Instant,
announcer: Option<TrackerAnnouncer>,
peer_id: [u8; 20],
}
impl BtSeedManager {
pub fn new(
connections: Vec<aria2_protocol::bittorrent::peer::connection::PeerConnection>,
piece_provider: Arc<dyn PieceDataProvider>,
config: BtSeedingConfig,
exit_condition: SeedExitCondition,
total_downloaded: u64,
) -> Self {
Self::build(
[0u8; 20],
connections,
piece_provider,
config,
exit_condition,
total_downloaded,
None,
CancellationToken::new(),
None,
[0u8; 20],
)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_info_hash(
info_hash: [u8; 20],
connections: Vec<aria2_protocol::bittorrent::peer::connection::PeerConnection>,
piece_provider: Arc<dyn PieceDataProvider>,
config: BtSeedingConfig,
exit_condition: SeedExitCondition,
total_downloaded: u64,
) -> Self {
Self::build(
info_hash,
connections,
piece_provider,
config,
exit_condition,
total_downloaded,
None,
CancellationToken::new(),
None,
[0u8; 20],
)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_choking_algo(
connections: Vec<aria2_protocol::bittorrent::peer::connection::PeerConnection>,
piece_provider: Arc<FileBackedPieceProvider>,
config: BtSeedingConfig,
exit_condition: SeedExitCondition,
total_downloaded: u64,
choking_algo: Option<ChokingAlgorithm>,
) -> Self {
Self::build(
[0u8; 20],
connections,
piece_provider,
config,
exit_condition,
total_downloaded,
choking_algo,
CancellationToken::new(),
None,
[0u8; 20],
)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_announcer(
info_hash: [u8; 20],
connections: Vec<aria2_protocol::bittorrent::peer::connection::PeerConnection>,
piece_provider: Arc<dyn PieceDataProvider>,
config: BtSeedingConfig,
exit_condition: SeedExitCondition,
total_downloaded: u64,
choking_algo: Option<ChokingAlgorithm>,
announcer: Option<TrackerAnnouncer>,
peer_id: [u8; 20],
) -> Self {
Self::build(
info_hash,
connections,
piece_provider,
config,
exit_condition,
total_downloaded,
choking_algo,
CancellationToken::new(),
announcer,
peer_id,
)
}
#[allow(clippy::too_many_arguments)]
pub fn new_with_cancel_token(
info_hash: [u8; 20],
connections: Vec<aria2_protocol::bittorrent::peer::connection::PeerConnection>,
piece_provider: Arc<dyn PieceDataProvider>,
config: BtSeedingConfig,
exit_condition: SeedExitCondition,
total_downloaded: u64,
cancel_token: CancellationToken,
) -> Self {
Self::build(
info_hash,
connections,
piece_provider,
config,
exit_condition,
total_downloaded,
None,
cancel_token,
None,
[0u8; 20],
)
}
#[allow(clippy::too_many_arguments)]
fn build(
info_hash: [u8; 20],
connections: Vec<aria2_protocol::bittorrent::peer::connection::PeerConnection>,
piece_provider: Arc<dyn PieceDataProvider>,
config: BtSeedingConfig,
exit_condition: SeedExitCondition,
total_downloaded: u64,
choking_algo: Option<ChokingAlgorithm>,
cancel_token: CancellationToken,
announcer: Option<TrackerAnnouncer>,
peer_id: [u8; 20],
) -> Self {
let upload_sessions: Vec<BtUploadSession> = connections
.into_iter()
.map(|conn| {
let mut session = BtUploadSession::new(conn, &config);
session.configure_message_validator(
piece_provider.num_pieces(),
piece_provider.piece_length(),
);
session
})
.collect();
let peer_stats: Vec<PeerStats> = upload_sessions
.iter()
.map(|session| {
let addr = session
.endpoint()
.and_then(|(ip, port)| format!("{ip}:{port}").parse().ok())
.unwrap_or_else(|| "0.0.0.0:0".parse().expect("valid unspecified address"));
PeerStats::new([0u8; 20], addr)
})
.collect();
let seeder_choke = BtSeederStateChoke::with_slots(config.max_peers_to_unchoke);
Self {
info_hash,
upload_sessions,
peer_stats,
piece_provider: Some(piece_provider),
config,
exit_condition,
total_downloaded,
total_uploaded: 0,
seeding_start_time: Instant::now(),
is_active: true,
seeder_choke,
choking_algo,
cancel_token,
peer_storage: None,
halt_requested: false,
last_choke_time: Instant::now(),
announcer,
peer_id,
}
}
pub fn with_peer_storage(
mut self,
peer_storage: std::sync::Arc<
std::sync::Mutex<crate::engine::bt_peer_storage::DefaultPeerStorage>,
>,
) -> Self {
self.peer_storage = Some(peer_storage);
self
}
pub async fn run_seeding_loop(&mut self) -> crate::error::Result<()> {
info!(
info_hash = ?self.info_hash,
"Seeding loop started (ratio={:?}, time={:?}, peers={})",
self.exit_condition.seed_ratio,
self.exit_condition.seed_time,
self.upload_sessions.len()
);
let mut tick = tokio::time::interval(SEED_TICK_INTERVAL);
loop {
if self.cancel_token.is_cancelled() {
info!("Seeding loop cancelled via cancellation token");
break;
}
if self.should_stop_seeding() {
self.halt_requested = true;
info!(
"Seed exit conditions met (uploaded={}, downloaded={}, duration={:?})",
self.total_uploaded,
self.total_downloaded,
self.seeding_duration()
);
break;
}
if let Some(announcer) = self.announcer.as_mut()
&& announcer.is_default_announce_ready()
&& let Some(result) = announcer
.announce(
&self.info_hash,
&self.peer_id,
self.total_downloaded,
0,
self.total_uploaded,
)
.await
{
debug!(
"[Seed] Re-announced to {} ({} seeders, {} leechers)",
result.tracker_url, result.seeders, result.leechers
);
}
self.handle_peer_messages().await;
self.remove_dead_sessions();
if self.upload_sessions.is_empty() {
info!("All upload sessions dead, exiting seeding loop");
break;
}
self.sync_sessions_to_stats();
if self.last_choke_time.elapsed().as_secs() >= CHOKE_ROUND_INTERVAL_SECS {
self.run_choke_round();
self.last_choke_time = Instant::now();
}
self.apply_choke_decisions().await;
self.update_total_uploaded();
tokio::select! {
_ = tick.tick() => {}
_ = self.cancel_token.cancelled() => {
info!("Seeding loop cancelled during tick wait");
break;
}
}
}
if let Some(announcer) = self.announcer.as_mut() {
announcer
.announce_stopped(
&self.info_hash,
&self.peer_id,
self.total_downloaded,
0,
self.total_uploaded,
)
.await;
}
self.is_active = false;
info!(
"Seeding loop ended: uploaded {} bytes in {:?}",
self.total_uploaded,
self.seeding_duration()
);
Ok(())
}
async fn handle_peer_messages(&mut self) {
let provider = match self.piece_provider.as_ref() {
Some(p) => Arc::clone(p),
None => return,
};
for session in &mut self.upload_sessions {
if session.is_dead() {
continue;
}
match tokio::time::timeout(
MSG_READ_TIMEOUT,
session.handle_incoming_messages(provider.as_ref()),
)
.await
{
Ok(Ok(bytes_uploaded)) => {
if bytes_uploaded > 0 {
debug!("Uploaded {} bytes to peer", bytes_uploaded);
}
}
Ok(Err(e)) => {
warn!("Upload session error: {}", e);
}
Err(_) => {
}
}
}
}
fn remove_dead_sessions(&mut self) {
let before = self.upload_sessions.len();
let dead_indices: Vec<usize> = self
.upload_sessions
.iter()
.enumerate()
.filter(|(_, s)| s.is_dead())
.map(|(i, _)| i)
.collect();
for idx in dead_indices.into_iter().rev() {
if let Some((ip, port)) = self.upload_sessions[idx].endpoint()
&& let Some(peer_storage) = &self.peer_storage
{
peer_storage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.return_peer_by_endpoint(&ip, port);
}
self.upload_sessions.remove(idx);
if idx < self.peer_stats.len() {
self.peer_stats.remove(idx);
}
}
self.peer_stats.truncate(self.upload_sessions.len());
let removed = before - self.upload_sessions.len();
if removed > 0 {
debug!("Removed {} dead upload sessions", removed);
}
}
fn sync_sessions_to_stats(&mut self) {
let len = self.upload_sessions.len().min(self.peer_stats.len());
for i in 0..len {
let session = &self.upload_sessions[i];
let stats = &mut self.peer_stats[i];
stats.peer_interested = session.is_peer_interested();
stats.uploaded_bytes = session.uploaded_bytes();
let elapsed = self.seeding_start_time.elapsed().as_secs_f64();
if elapsed > 0.0 {
stats.upload_speed = session.uploaded_bytes() as f64 / elapsed;
}
}
}
fn run_choke_round(&mut self) {
let mut peer_stats = std::mem::take(&mut self.peer_stats);
let mut peers_mut: Vec<&mut PeerStats> = peer_stats.iter_mut().collect();
self.seeder_choke.execute_choke(&mut peers_mut[..]);
self.peer_stats = peer_stats;
}
async fn apply_choke_decisions(&mut self) {
let len = self.upload_sessions.len().min(self.peer_stats.len());
for i in 0..len {
let stats_am_choking = self.peer_stats[i].am_choking;
let session = &mut self.upload_sessions[i];
if stats_am_choking && !session.is_peer_choked() {
if let Err(e) = session.choke_peer().await {
warn!("Failed to choke peer: {}", e);
}
} else if !stats_am_choking && session.is_peer_choked() {
if let Err(e) = session.unchoke_peer().await {
warn!("Failed to unchoke peer: {}", e);
}
}
}
}
fn update_total_uploaded(&mut self) {
let mut total = 0u64;
for session in &self.upload_sessions {
total += session.uploaded_bytes();
}
self.total_uploaded = total;
}
pub fn should_stop_seeding(&self) -> bool {
if let Some(ratio) = self.exit_condition.seed_ratio
&& SeedExitCondition::check_seed_condition(
self.total_uploaded,
self.total_downloaded,
ratio,
)
{
return true;
}
if let Some(time) = self.exit_condition.seed_time
&& SeedExitCondition::check_seed_time(self.seeding_start_time, time.as_secs(), true)
{
return true;
}
false
}
pub fn should_exit(&self) -> bool {
self.should_stop_seeding()
}
pub fn halt_requested(&self) -> bool {
self.halt_requested
}
pub fn total_uploaded(&self) -> u64 {
self.total_uploaded
}
pub fn take_announcer(&mut self) -> Option<TrackerAnnouncer> {
self.announcer.take()
}
pub fn total_downloaded(&self) -> u64 {
self.total_downloaded
}
pub fn get_upload_stats(&self) -> (u64, u64) {
let elapsed_secs = self.seeding_start_time.elapsed().as_secs();
let upload_speed = self.total_uploaded.checked_div(elapsed_secs).unwrap_or(0);
(self.total_uploaded, upload_speed)
}
pub fn seeding_duration(&self) -> Duration {
self.seeding_start_time.elapsed()
}
pub fn is_active(&self) -> bool {
self.is_active
}
pub fn info_hash(&self) -> &[u8; 20] {
&self.info_hash
}
pub fn num_sessions(&self) -> usize {
self.upload_sessions.len()
}
pub fn record_upload(&mut self, bytes: u64) {
self.total_uploaded += bytes;
}
pub fn cancel(&self) {
self.cancel_token.cancel();
}
pub fn cancellation_token(&self) -> CancellationToken {
self.cancel_token.clone()
}
}