Skip to main content

BtDownloadCommand

Struct BtDownloadCommand 

Source
pub struct BtDownloadCommand {
    pub choking_algo: Option<ChokingAlgorithm>,
    pub multi_file_layout: Option<MultiFileLayout>,
    pub download_path_lock: Option<DownloadPathLock>,
    /* private fields */
}

Fields§

§choking_algo: Option<ChokingAlgorithm>§multi_file_layout: Option<MultiFileLayout>§download_path_lock: Option<DownloadPathLock>

Download path lock held for the lifetime of this command. Prevents other aria2 instances from writing to the same output directory.

Implementations§

Source§

impl BtDownloadCommand

Source

pub fn new( gid: GroupId, torrent_bytes: &[u8], options: &DownloadOptions, output_dir: Option<&str>, ) -> Result<Self>

Source

pub async fn group(&self) -> RwLockReadGuard<'_, RequestGroup>

Source

pub fn on_peer_choke(&mut self, peer_idx: usize)

Source

pub fn on_peer_unchoke(&mut self, peer_idx: usize)

Source

pub fn on_data_received_from_peer(&mut self, peer_idx: usize, bytes: u64)

Source

pub fn check_snubbed_peers(&mut self) -> Vec<usize>

Source

pub fn add_peer_to_tracking( &mut self, peer_id: [u8; 8], addr: SocketAddr, ) -> usize

Source

pub fn select_best_peer_for_request(&self) -> Option<usize>

Source

pub async fn handle_snubbed_peer(&mut self, peer_idx: usize) -> Result<()>

Source

pub fn on_piece_received(&mut self, peer_idx: usize, bytes: u64)

Source

pub fn mark_peer_snubbed(&mut self, peer_idx: usize)

Explicitly mark a peer as snubbed (algorithm-level snubbing).

This adds the peer to the explicit snubbed set, causing them to receive a score of -1000 on the next choke rotation, ensuring they are always choked.

Source

pub fn is_explicitly_snubbed(&self, peer_idx: usize) -> bool

Check if a peer is explicitly snubbed at the algorithm level.

Source

pub async fn announce_to_public_tracker( tracker_url: &str, info_hash: &[u8; 20], peer_id: &[u8; 20], total_size: u64, ) -> Result<Vec<(String, u16)>, String>

Source

pub async fn write_piece_to_multi_files( layout: &MultiFileLayout, piece_idx: u32, piece_data: &[u8], piece_length: u32, ) -> Result<()>

Source

pub async fn write_piece_to_multi_files_coalesced( layout: &MultiFileLayout, piece_idx: u32, piece_data: &[u8], piece_length: u32, ) -> Result<()>

Wrapper around crate::engine::bt_piece_downloader::write_piece_to_multi_files_coalesced.

Prefer this over write_piece_to_multi_files for production use — it merges adjacent writes within a 4 KiB gap, reducing syscall count.

Source

pub fn is_multi_file(&self) -> bool

Source

pub fn get_multi_file_layout(&self) -> Option<&MultiFileLayout>

Source

pub fn set_progress_manager(&mut self, manager: BtProgressManager)

设置 BT 进度管理器

Enable BT download progress persistence for resume support.

When enabled, the engine periodically saves piece completion bitfield, peer list, and download statistics to a .aria2 file in INI format. On restart, the progress is loaded to skip already-completed pieces.

§Arguments
§Example
use aria2_core::engine::bt_progress_info_file::BtProgressManager;
use std::path::PathBuf;

let save_dir = PathBuf::from("/tmp/aria2");
let progress_mgr = BtProgressManager::new(&save_dir).expect("failed to create progress manager");
// Pass progress_mgr to BtDownloadCommand::set_progress_manager()
let _mgr = progress_mgr;
Source

pub fn set_progress_save_interval(&mut self, interval_secs: u64)

Set the interval (in seconds) between progress save operations.

§Arguments
  • interval_secs - Save interval in seconds (default: 60)
Source

pub fn set_lpd_manager(&mut self, manager: Arc<LpdManager>)

Enable Local Peer Discovery (LPD, BEP 14) for LAN peer finding.

When enabled, the engine announces its active downloads via UDP multicast to 239.192.152.143:6771 and listens for peers on the same network.

§Arguments
  • manager - An initialized LpdManager, wrapped in Arc
Source

pub fn set_hook_manager(&mut self, manager: Arc<HookManager>)

Register a post-download hook chain for completion/error callbacks.

Hooks execute sequentially after download completes or fails. Built-in hook types: Move, Rename, Touch, Exec (shell command). A single hook failure does not block subsequent hooks.

§Arguments
  • manager - A configured HookManager with registered hooks, wrapped in Arc
§Example
use std::collections::HashMap;
use std::sync::Arc;
use aria2_core::engine::bt_post_download_handler::{HookManager, HookConfig, MoveHook, ExecHook};

let config = HookConfig::default();
let mut hooks = HookManager::new(config);
hooks.add_hook(Box::new(MoveHook::new("/completed".into(), true)));
hooks.add_hook(Box::new(ExecHook::new("notify.sh".into(), HashMap::new())));
// Pass Arc::new(hooks) to BtDownloadCommand::set_hook_manager()
let _hooks = Arc::new(hooks);
Source

pub fn get_progress_manager(&self) -> Option<&BtProgressManager>

获取进度管理器引用(用于测试和外部访问)

Source

pub fn get_lpd_manager(&self) -> Option<&Arc<LpdManager>>

获取 LPD 管理器引用(用于测试和外部访问)

Source

pub fn get_hook_manager(&self) -> Option<&Arc<HookManager>>

获取钩子管理器引用(用于测试和外部访问)

Source

pub fn add_pex_peer(&mut self, peer_addr: PeerAddr)

Add a peer address to the known peers list for PEX exchange

Source

pub fn set_pex_known_peers(&mut self, peers: Vec<PeerAddr>)

Set the list of known peers for PEX exchange

Source

pub fn get_pex_known_peers(&self) -> &[PeerAddr]

Get reference to PEX known peers list

Source

pub fn set_pex_send_interval(&mut self, interval_secs: u64)

Set custom PEX send interval (default 60 seconds)

Source

pub fn should_send_pex(&self) -> bool

Check if it’s time to send a PEX message based on rate limiting

Source

pub fn update_pex_last_send(&mut self)

Update the last PEX send timestamp

Source

pub fn endgame_state_mut(&mut self) -> &mut EndgameState

Get a mutable reference to the EndgameState for tracking duplicate requests

Source

pub fn endgame_state(&self) -> &EndgameState

Get an immutable reference to the EndgameState

Source

pub fn record_bad_piece_for_peer( &mut self, peer_idx: usize, piece_index: u32, ) -> Result<bool, ()>

Record that a specific peer sent invalid piece data (hash verification failed).

This method:

  1. Increments the peer’s bad_data_count in the choking algorithm’s PeerStats
  2. If the count reaches crate::engine::peer_stats::BAD_DATA_THRESHOLD, automatically bans the peer with a reason message
  3. Logs the event at WARN level
§Arguments
  • peer_idx - The index of the peer in the choking algorithm’s peer list
  • piece_index - The index of the piece that failed verification
§Returns
  • Ok(true) if the peer was banned as a result of this call
  • Ok(false) if the peer was not banned (count below threshold)
  • Err(()) if the peer index is invalid or choking algorithm is not configured
Source

pub fn record_valid_piece_for_peer(&mut self, peer_idx: usize)

Record that a valid, verified piece was received from a peer.

This triggers gradual recovery by decrementing the peer’s bad_data_count. Call this after successful hash verification to allow peers to recover reputation.

§Arguments
  • peer_idx - The index of the peer in the choking algorithm’s peer list
Source

pub fn is_peer_banned(&self, peer_idx: usize) -> bool

Check if a peer is currently banned.

§Arguments
  • peer_idx - The index of the peer in the choking algorithm’s peer list
§Returns
  • true if the peer is banned or peer not found
  • false if the peer exists and is not banned
Source

pub fn get_peer_stats(&self, peer_idx: usize) -> Option<&PeerStats>

Get a reference to a peer’s stats for RPC/display purposes.

Returns None if the peer doesn’t exist or no choking algorithm is configured.

Source

pub fn init_web_seed_manager(&mut self, piece_length: u32, total_length: u64)

Initialize the web seed manager if web seeds are configured.

This should be called after the torrent metadata is parsed and before the download loop starts.

§Arguments
  • piece_length - Length of each piece in the torrent
  • total_length - Total file length
Source

pub fn get_web_seed_manager(&self) -> Option<&WebSeedManager>

Get a reference to the web seed manager.

Source

pub fn get_web_seed_manager_mut(&mut self) -> Option<&mut WebSeedManager>

Get a mutable reference to the web seed manager.

Source

pub fn has_web_seeds(&self) -> bool

Check if web seeds are available.

Source

pub fn web_seed_stats(&self) -> Option<&WebSeedStats>

Get web seed download statistics.

Source

pub fn check_and_start_seeding( &mut self, piece_picker: &PiecePicker, meta: &TorrentMeta, connections: Vec<PeerConnection>, piece_provider: Arc<dyn PieceDataProvider>, ) -> Result<bool>

Check if download is complete and start seeding if enabled.

This method should be called after the download loop completes. It initializes the seed manager if:

  • All pieces are complete
  • Seeding is enabled (seed_ratio > 0 or seed_time > 0)
§Arguments
  • piece_picker - Reference to the piece picker to check completion
  • meta - Torrent metadata
  • connections - Active peer connections to use for seeding
  • piece_provider - Provider for piece data (from downloaded files)
§Returns
  • Ok(true) if seeding was started
  • Ok(false) if seeding was not started (not complete or disabled)
Source

pub fn get_seed_manager(&self) -> Option<&BtSeedManager>

Get a reference to the seed manager.

Source

pub fn get_seed_manager_mut(&mut self) -> Option<&mut BtSeedManager>

Get a mutable reference to the seed manager.

Source

pub fn is_seeding(&self) -> bool

Check if seeding is active.

Source

pub fn get_seed_stats(&self) -> Option<SeedStats>

Get seeding statistics.

Returns None if not seeding.

Source§

impl BtDownloadCommand

Source

pub fn check_pex_support( local_extension_ids: &[Option<u8>], remote_extension_ids: &[Option<u8>], ) -> bool

Check if both local and remote peer support ut_pex extension

Source

pub fn maybe_send_pex(&mut self, remote_peer_addr: &PeerAddr) -> Option<Vec<u8>>

Build and optionally send a PEX message to connected peers Returns the encoded PEX message (or None if not ready to send)

Source

pub fn handle_incoming_pex( &mut self, pex_data: &[u8], local_addr: &PeerAddr, ) -> Result<(Vec<PeerAddr>, Vec<PeerAddr>)>

Process an incoming PEX message and extract discovered/dropped peers

Source

pub async fn connect_to_pex_discovered_peers( &mut self, new_peers: &[PeerAddr], _info_hash_raw: &[u8; 20], _num_pieces: u32, active_connections: &[BtPeerConn], ) -> usize

Connect to peers discovered via PEX

This method attempts to establish connections with peers that were discovered through PEX (Peer Exchange, BEP 11). It’s called when new peers are added to the PEX known peers list.

§Arguments
  • new_peers - List of peer addresses discovered via PEX
  • info_hash_raw - Torrent info hash for handshake
  • num_pieces - Total number of pieces for bitfield size
  • active_connections - Current active connections (to avoid duplicates)
§Returns
  • Number of successfully connected new peers
Source§

impl BtDownloadCommand

Source

pub async fn run_seeding_phase( &mut self, connections: Vec<BtPeerConn>, piece_length: u32, num_pieces: u32, ) -> Result<()>

Trait Implementations§

Source§

impl Command for BtDownloadCommand

Source§

fn execute<'life0, 'async_trait>( &'life0 mut self, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Source§

fn status(&self) -> CommandStatus

Source§

fn timeout(&self) -> Option<Duration>

Source§

fn started_at(&self) -> Option<Instant>

Returns the instant at which this command started executing, if the engine has informed the command via [set_started_at]. Read more
Source§

fn set_started_at(&mut self, _instant: Instant)

Called by the engine immediately before the command is spawned onto a background task. The default implementation is a no-op; commands that store the instant can expose it through [started_at].

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more