mod constructors;
mod seeding_loop;
#[cfg(test)]
mod tests;
pub mod types;
pub use types::SeedExitCondition;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio_util::sync::CancellationToken;
use crate::engine::bt_choke_manager::BtSeederStateChoke;
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;
use crate::request::request_group::{AtomicProgress, BtPeerSnapshot, ConnectionState};
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],
incoming_peers:
Option<tokio::sync::mpsc::Receiver<crate::engine::bt_peer_listener::IncomingPeer>>,
upload_progress: Option<Arc<AtomicProgress>>,
connection_state: Option<Arc<ConnectionState>>,
peer_snapshot_store: Option<Arc<std::sync::RwLock<Vec<BtPeerSnapshot>>>>,
}
impl BtSeedManager {
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_f64();
let upload_speed = if elapsed_secs > 0.0 {
(self.total_uploaded as f64 / elapsed_secs) as u64
} else {
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 = self.total_uploaded.saturating_add(bytes);
}
pub(crate) fn set_total_uploaded(&mut self, total_uploaded: u64) {
self.total_uploaded = total_uploaded;
self.publish_upload_stats();
}
pub fn cancel(&self) {
self.cancel_token.cancel();
}
pub fn cancellation_token(&self) -> CancellationToken {
self.cancel_token.clone()
}
pub(crate) fn set_upload_progress(&mut self, progress: Arc<AtomicProgress>) {
self.upload_progress = Some(progress);
self.publish_upload_stats();
}
pub(crate) fn set_connection_state(
&mut self,
connection_state: Arc<ConnectionState>,
peer_snapshot_store: Arc<std::sync::RwLock<Vec<BtPeerSnapshot>>>,
) {
self.connection_state = Some(connection_state);
self.peer_snapshot_store = Some(peer_snapshot_store);
self.publish_connection_state();
}
fn clear_connection_state(&self) {
if let Some(connection_state) = self.connection_state.as_ref() {
connection_state.set_bt(0);
}
if let Some(store) = self.peer_snapshot_store.as_ref() {
*store
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = Vec::new();
}
}
fn publish_connection_state(&self) {
if let Some(connection_state) = self.connection_state.as_ref() {
connection_state.set_bt(self.num_sessions());
}
if let Some(store) = self.peer_snapshot_store.as_ref() {
*store
.write()
.unwrap_or_else(std::sync::PoisonError::into_inner) = self.peer_snapshots();
}
}
fn peer_snapshots(&self) -> Vec<BtPeerSnapshot> {
self.upload_sessions
.iter()
.enumerate()
.filter_map(|(index, session)| {
let addr = session.remote_endpoint()?;
let stats = self.peer_stats.get(index);
Some(BtPeerSnapshot {
peer_id: session.remote_peer_id().unwrap_or([0; 20]),
addr,
is_incoming: true,
source: crate::request::request_group::BtPeerSource::Incoming,
bitfield: None,
uploaded_bytes: session.uploaded_bytes(),
downloaded_bytes: 0,
upload_speed: stats.map_or(0.0, |stats| stats.upload_speed),
download_speed: 0.0,
avg_upload_speed: stats.map_or(0, |stats| stats.avg_upload_speed),
avg_download_speed: 0,
am_choking: session.is_peer_choked(),
peer_choking: false,
seeder: Some(false),
connection_duration_secs: stats
.map_or(0, |stats| stats.connection_duration_secs()),
last_data_age_secs: stats.map_or(0, |stats| {
stats
.last_data_time
.map(|time| time.elapsed().as_secs())
.unwrap_or_else(|| stats.connection_duration_secs())
}),
is_snubbed: stats.is_some_and(|stats| stats.is_snubbed),
is_banned: false,
})
})
.collect()
}
fn publish_upload_stats(&self) {
if let Some(progress) = self.upload_progress.as_ref() {
progress.set_upload_length(self.total_uploaded);
progress.set_upload_speed(self.get_upload_stats().1);
}
}
}