aria2-core 0.3.13

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
//! Piece picker module
//!
//! Implements piece selection strategies for BitTorrent downloads.
//! Based on BEP 0019 (WebSeed) and various piece picking algorithms.

use crate::segment::Bitfield;

mod selection;
#[cfg(test)]
mod tests;
mod types;

pub use types::{
    PickedPiece, PieceInfo, PiecePickerConfig, PiecePriorityMode, PieceSelectionStrategy,
};

/// Default remaining-piece count at or below which end-game tracking
/// activates. Mirrors aria2's `BT_ENDGAME_THRESHOLD`.
pub const DEFAULT_ENDGAME_THRESHOLD: usize = 20;

/// Piece picker — selects the next piece to download based on the
/// configured strategy, peer bitfield frequency data, and priority mode.
///
/// Maintains internal state for end-game candidate tracking and
/// per-piece frequency counters used by the rarest-first algorithm.
///
/// # Complexity
///
/// Sequential orders (`Forward` / `Backward`) and unrestricted rarest-first
/// picks are amortised **O(1)** thanks to monotone cursors: every piece before
/// the cursor is known to be completed or unavailable. The rarest order is
/// rebuilt in O(n log n) when frequencies change. Peer-restricted selection
/// remains O(n), because a different peer bitfield can make any earlier piece
/// unavailable.
pub struct PiecePicker {
    /// Total number of pieces in the torrent
    num_pieces: u32,
    /// Active selection strategy
    strategy: PieceSelectionStrategy,
    /// Active priority mode
    priority_mode: PiecePriorityMode,
    /// Per-piece availability frequency (from peer bitfields)
    frequencies: Vec<u32>,
    /// Whether `frequencies` came from an authoritative swarm snapshot.
    /// Before the first snapshot, callers may use the picker without peer
    /// availability; afterwards, zero means no connected peer has the piece.
    has_availability_snapshot: bool,
    /// Piece indexes sorted by availability, then by index for stable ties.
    rarest_order: Vec<u32>,
    /// Cursor into `rarest_order` for unrestricted normal-mode selection.
    rarest_cursor: usize,
    /// Per-piece completion tracking (true = piece verified and written)
    completed: Bitfield,
    /// Per-piece selection filter (true = piece is requested by this task).
    /// Every selection strategy consults this same fact.
    allowed: Bitfield,
    /// Per-piece in-progress tracking (true = piece is being downloaded)
    in_progress: Bitfield,
    /// Pieces exclusively leased to a non-peer source such as a WebSeed.
    /// End-game duplicate requests must not compete with these owners.
    reserved: Bitfield,
    /// Per-piece priority (0 = default, higher = more important)
    priorities: Vec<u8>,
    /// Explicitly prioritized pieces, in the order in which they are tried.
    /// This models aria2's `PriorityPieceSelector` wrapper.
    priority_pieces: Vec<u32>,
    /// Indices of pieces that are candidates for end-game mode
    endgame_candidates: Vec<usize>,
    /// Number of selected pieces marked completed.
    completed_allowed_count: usize,
    /// Number of pieces selected by the current filter.
    allowed_count: usize,
    /// Forward scan cursor: every piece with index `< head_cursor` is
    /// completed or in progress. Only ever moves forward (or is reset
    /// backwards by [`PiecePicker::reopen`]).
    head_cursor: usize,
    /// Backward scan cursor stored as `index + 1`, so `0` means "exhausted".
    tail_cursor: usize,
    /// Remaining-piece count at or below which end-game candidates are tracked
    endgame_threshold: usize,
    /// xorshift64* state for the `Random` / `Geometric` orders
    rng_state: u64,
}

impl PiecePicker {
    /// Create a new picker for a torrent with `num_pieces` pieces.
    pub fn new(num_pieces: u32) -> Self {
        let n = num_pieces as usize;
        let mut picker = Self {
            num_pieces,
            strategy: PieceSelectionStrategy::RarestFirst,
            priority_mode: PiecePriorityMode::RarestFirst,
            frequencies: vec![0; n],
            has_availability_snapshot: false,
            rarest_order: (0..num_pieces).collect(),
            rarest_cursor: 0,
            completed: Bitfield::new(n),
            allowed: Bitfield::all_set(n),
            in_progress: Bitfield::new(n),
            reserved: Bitfield::new(n),
            priorities: vec![0; n],
            priority_pieces: Vec::new(),
            endgame_candidates: Vec::new(),
            completed_allowed_count: 0,
            allowed_count: n,
            head_cursor: 0,
            tail_cursor: n,
            endgame_threshold: DEFAULT_ENDGAME_THRESHOLD,
            rng_state: Self::seed(),
        };
        picker.refresh_endgame_candidates();
        picker
    }

    /// Derive a non-zero RNG seed from the standard library's randomised
    /// hasher, avoiding an external `rand` dependency in the protocol crate.
    fn seed() -> u64 {
        use std::hash::{BuildHasher, Hasher};
        let s = std::collections::hash_map::RandomState::new()
            .build_hasher()
            .finish();
        s | 1
    }

    /// Advance the xorshift64* generator and return the next value.
    fn next_rand(&mut self) -> u64 {
        let mut x = self.rng_state;
        x ^= x >> 12;
        x ^= x << 25;
        x ^= x >> 27;
        self.rng_state = x;
        x.wrapping_mul(0x2545_F491_4F6C_DD1D)
    }

    /// Set the base selection strategy.
    pub fn set_strategy(&mut self, strategy: PieceSelectionStrategy) {
        self.strategy = strategy;
    }

    /// Set the piece priority mode.
    pub fn set_priority_mode(&mut self, mode: PiecePriorityMode) {
        self.priority_mode = mode;
    }

    /// Install a prioritized piece sequence used before the normal selector.
    pub fn set_priority_pieces(&mut self, mut pieces: Vec<u32>) {
        pieces.retain(|&piece| piece < self.num_pieces);
        pieces.sort_unstable();
        pieces.dedup();
        for index in (1..pieces.len()).rev() {
            let swap = (self.next_rand() % (index as u64 + 1)) as usize;
            pieces.swap(index, swap);
        }
        self.priority_pieces = pieces;
    }

    /// Return the currently installed explicit priority sequence.
    pub fn priority_pieces(&self) -> &[u32] {
        &self.priority_pieces
    }

    /// Restrict selection and selective completion to the given piece
    /// indexes.
    ///
    /// The completion bitfield remains global: unselected pieces that were
    /// already present can still be persisted and reported, but they do not
    /// contribute to selective-download completion or future selection.
    pub fn set_allowed_pieces(&mut self, pieces: &[u32]) {
        self.allowed.clear_all();
        for &piece in pieces {
            self.allowed.set(piece as usize);
        }
        self.allowed_count = (0..self.num_pieces as usize)
            .filter(|&i| self.allowed.test(i))
            .count();
        self.completed_allowed_count = (0..self.num_pieces as usize)
            .filter(|&i| self.completed.test(i) && self.allowed.test(i))
            .count();
        self.head_cursor = 0;
        self.tail_cursor = self.num_pieces as usize;
        self.rarest_cursor = 0;
        self.refresh_endgame_candidates();
    }

    /// Whether a piece belongs to the current selective-download set.
    pub fn is_allowed(&self, index: u32) -> bool {
        self.allowed.test(index as usize)
    }

    /// Whether an incomplete piece is currently selectable by the normal
    /// peer-source picker. Used by the engine work queue to defer reserved or
    /// currently unavailable pieces without changing picker priority order.
    pub(crate) fn is_selectable(&self, index: u32) -> bool {
        let index = index as usize;
        index < self.num_pieces as usize
            && self.is_available(index)
            && (!self.has_availability_snapshot || self.frequencies[index] > 0)
    }

    /// Number of pieces selected by the current filter.
    pub fn allowed_count(&self) -> usize {
        self.allowed_count
    }

    /// Override the remaining-piece count at which end-game mode activates.
    pub fn set_endgame_threshold(&mut self, threshold: usize) {
        self.endgame_threshold = threshold;
        self.refresh_endgame_candidates();
    }

    /// Set the explicit priority of a piece (used by the `Priority` strategy).
    pub fn set_priority(&mut self, index: u32, priority: u8) {
        let i = index as usize;
        if i < self.num_pieces as usize {
            self.priorities[i] = priority;
        }
    }

    /// Pick the next piece index using the configured strategy.
    ///
    /// `bitfield` is the peer's have-bitfield (MSB-first), `nbits` is the
    /// number of valid bits (typically `num_pieces`). Returns `None` when the
    /// peer has nothing we still need.
    pub fn select(&mut self, bitfield: &[u8], nbits: usize) -> Option<u32> {
        self.pick_internal(Some(bitfield), nbits, false)
    }

    /// Pick the next piece without a peer restriction.
    ///
    /// In end-game mode (remaining pieces at or below the threshold) pieces
    /// already in flight become eligible again, so they can be requested from
    /// several peers at once.
    pub fn pick_next(&mut self) -> Option<u32> {
        let allow_in_progress = self.endgame_active();
        let n = self.num_pieces as usize;
        self.pick_internal(None, n, allow_in_progress)
    }

    /// Pick the next piece without peer restrictions or end-game duplicates.
    ///
    /// The BT scheduler uses this when its own end-game threshold says normal
    /// selection is still active. Keeping the flag explicit avoids coupling
    /// the protocol picker to a caller-owned threshold.
    pub fn pick_next_without_endgame(&mut self) -> Option<u32> {
        let n = self.num_pieces as usize;
        self.pick_internal(None, n, false)
    }

    /// Whether end-game mode is currently active.
    pub fn endgame_active(&self) -> bool {
        let remaining = self.remaining_count();
        remaining > 0 && remaining <= self.endgame_threshold
    }

    /// Recompute the end-game candidate list (incomplete pieces).
    ///
    /// O(n), but only runs once end-game mode is active, i.e. at most
    /// `endgame_threshold` times per download.
    fn refresh_endgame_candidates(&mut self) {
        self.endgame_candidates.clear();
        if !self.endgame_active() {
            return;
        }
        for i in 0..self.num_pieces as usize {
            if self.allowed.test(i) && !self.completed.test(i) {
                self.endgame_candidates.push(i);
            }
        }
    }

    /// Return the list of piece indices that are end-game candidates.
    pub fn endgame_candidates(&self) -> &[usize] {
        &self.endgame_candidates
    }

    /// Update per-piece frequency data from a peer frequency slice.
    pub fn set_frequencies_from_peers(&mut self, freqs: &[usize]) {
        self.has_availability_snapshot = true;
        self.frequencies.fill(0);
        let len = freqs.len().min(self.frequencies.len());
        for (dst, src) in self.frequencies.iter_mut().zip(freqs.iter()).take(len) {
            *dst = *src as u32;
        }
        self.rarest_order.sort_unstable_by_key(|&index| {
            let index = index as usize;
            (self.frequencies[index], index)
        });
        self.rarest_cursor = 0;
    }

    /// Iterator over all pieces, yielding [`PieceInfo`] for each.
    pub fn pieces_iter(&self) -> impl Iterator<Item = PieceInfo> + '_ {
        let n = self.num_pieces as usize;
        (0..n).map(move |i| PieceInfo {
            index: i as u32,
            frequency: self.frequencies[i],
            is_completed: self.completed.test(i),
            in_progress: self.in_progress.test(i),
            priority: self.priorities[i],
        })
    }

    /// Return info about a specific piece, or `None` if out of range.
    pub fn get_piece_info(&self, index: u32) -> Option<PieceInfo> {
        let i = index as usize;
        if i >= self.num_pieces as usize {
            return None;
        }
        Some(PieceInfo {
            index,
            frequency: self.frequencies[i],
            is_completed: self.completed.test(i),
            in_progress: self.in_progress.test(i),
            priority: self.priorities[i],
        })
    }

    /// Return the current priority mode.
    pub fn priority_mode(&self) -> PiecePriorityMode {
        self.priority_mode
    }

    /// Number of pieces not yet completed. O(1).
    pub fn remaining_count(&self) -> usize {
        self.allowed_count()
            .saturating_sub(self.completed_allowed_count)
    }

    /// Mark a piece as completed.
    ///
    /// Idempotent: marking an already-completed piece is a no-op. Also clears
    /// the in-progress flag, since a completed piece is no longer in flight.
    ///
    /// # Panics
    /// Panics if `index` is out of range in debug builds.
    pub fn mark_completed(&mut self, index: u32) {
        let i = index as usize;
        debug_assert!(
            i < self.num_pieces as usize,
            "mark_completed: index out of range"
        );
        if i >= self.num_pieces as usize {
            return;
        }
        if !self.completed.test(i) {
            self.completed.set(i);
            if self.allowed.test(i) {
                self.completed_allowed_count += 1;
            }
        }
        self.in_progress.clear(i);
        self.reserved.clear(i);
        self.refresh_endgame_candidates();
    }

    /// Mark a piece as being downloaded (or release it back to the pool).
    ///
    /// Releasing a piece (`in_progress = false`) rewinds the sequential
    /// cursors so the piece is picked up again by later scans.
    ///
    /// # Panics
    /// Panics if `index` is out of range in debug builds.
    pub fn mark_in_progress(&mut self, index: u32, in_progress: bool) {
        let i = index as usize;
        debug_assert!(
            i < self.num_pieces as usize,
            "mark_in_progress: index out of range"
        );
        if i >= self.num_pieces as usize {
            return;
        }
        if in_progress {
            self.in_progress.set(i);
        } else {
            self.in_progress.clear(i);
        }
        if !in_progress {
            self.reopen(i);
        }
    }

    /// Whether a piece is currently being downloaded.
    pub fn is_in_progress(&self, index: u32) -> bool {
        let i = index as usize;
        i < self.num_pieces as usize && self.in_progress.test(i)
    }

    /// Reserve a piece for an exclusive non-peer source.
    pub fn mark_reserved(&mut self, index: u32, reserved: bool) {
        let i = index as usize;
        if i >= self.num_pieces as usize {
            return;
        }
        if reserved {
            self.reserved.set(i);
        } else {
            self.reserved.clear(i);
            self.reopen(i);
        }
    }

    /// Whether a non-peer source currently owns this piece.
    pub fn is_reserved(&self, index: u32) -> bool {
        let i = index as usize;
        i < self.num_pieces as usize && self.reserved.test(i)
    }

    /// Whether a piece has been completed and verified.
    pub fn is_completed(&self, index: u32) -> bool {
        let i = index as usize;
        i < self.num_pieces as usize && self.completed.test(i)
    }

    /// Export completed pieces as a bitfield byte vector (MSB-first).
    pub fn export_bitfield(&self) -> Vec<u8> {
        self.completed.as_bytes().to_vec()
    }

    /// Export the currently wanted piece set as an MSB-first bitfield.
    ///
    /// In-progress and reserved pieces remain wanted: a peer may still be a
    /// useful source for retry, end-game, or WebSeed-shared work. Only pieces
    /// excluded by selection or already verified are removed.
    pub(crate) fn missing_pieces_bitfield(&self) -> Vec<u8> {
        self.allowed
            .as_bytes()
            .iter()
            .zip(self.completed.as_bytes())
            .map(|(allowed, completed)| *allowed & !*completed)
            .collect()
    }

    /// Check if all pieces are completed. O(1).
    pub fn is_complete(&self) -> bool {
        self.completed_allowed_count == self.allowed_count()
    }
}