1use std::cmp::Ordering as CmpOrdering;
7use std::collections::{BTreeSet, HashMap, HashSet};
8use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
9use std::sync::Arc;
10use std::time::{Duration, Instant};
11
12use bytes::Bytes;
13use parking_lot::RwLock;
14use rand::seq::SliceRandom;
15
16use crate::peer::bitfield::Bitfield;
17use crate::peer::error::PeerError;
18
19pub const BLOCK_SIZE: u32 = 16384;
21
22pub const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
24
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
27pub struct BlockRequest {
28 pub piece_index: u32,
30 pub offset: u32,
32 pub length: u32,
34}
35
36impl BlockRequest {
37 pub fn new(piece_index: u32, offset: u32, length: u32) -> Self {
39 Self {
40 piece_index,
41 offset,
42 length,
43 }
44 }
45}
46
47#[derive(Debug, Clone)]
49pub struct Block {
50 pub piece_index: u32,
52 pub offset: u32,
54 pub data: Bytes,
56}
57
58impl Block {
59 pub fn new(piece_index: u32, offset: u32, data: Bytes) -> Self {
61 Self {
62 piece_index,
63 offset,
64 data,
65 }
66 }
67
68 pub fn request(&self) -> BlockRequest {
70 BlockRequest {
71 piece_index: self.piece_index,
72 offset: self.offset,
73 length: self.data.len() as u32,
74 }
75 }
76}
77
78#[allow(dead_code)]
80pub fn compute_block_count(piece_length: u64, block_size: u32) -> u32 {
81 piece_length.div_ceil(block_size as u64) as u32
82}
83
84#[allow(dead_code)]
86pub fn compute_block_length(piece_length: u64, block_index: u32, block_size: u32) -> u32 {
87 let offset = block_index as u64 * block_size as u64;
88 let remaining = piece_length.saturating_sub(offset);
89 remaining.min(block_size as u64) as u32
90}
91
92#[derive(Debug)]
94struct PieceState {
95 blocks: HashMap<u32, Bytes>,
96 pending_blocks: HashMap<u32, Instant>,
97 piece_length: u32,
98 #[allow(dead_code)]
99 started_at: Instant,
100}
101
102impl PieceState {
103 fn new(piece_length: u32) -> Self {
104 Self {
105 blocks: HashMap::new(),
106 pending_blocks: HashMap::new(),
107 piece_length,
108 started_at: Instant::now(),
109 }
110 }
111
112 fn is_complete(&self) -> bool {
113 let block_count = self.piece_length.div_ceil(BLOCK_SIZE);
114 self.blocks.len() as u32 == block_count
115 }
116
117 fn assemble(&self) -> Bytes {
118 let mut data = Vec::with_capacity(self.piece_length as usize);
119 let block_count = self.piece_length.div_ceil(BLOCK_SIZE);
120
121 for i in 0..block_count {
122 let offset = i * BLOCK_SIZE;
123 if let Some(block) = self.blocks.get(&offset) {
124 data.extend_from_slice(block);
125 }
126 }
127
128 Bytes::from(data)
129 }
130
131 fn expired_requests(&self) -> Vec<u32> {
132 let now = Instant::now();
133 self.pending_blocks
134 .iter()
135 .filter(|(_, &sent_at)| now.duration_since(sent_at) > REQUEST_TIMEOUT)
136 .map(|(&offset, _)| offset)
137 .collect()
138 }
139}
140
141#[derive(Debug, Clone, Copy)]
142struct PieceWithAvailability {
143 availability: u32,
144 piece_index: u32,
145}
146
147impl PartialEq for PieceWithAvailability {
148 fn eq(&self, other: &Self) -> bool {
149 self.availability == other.availability && self.piece_index == other.piece_index
150 }
151}
152
153impl Eq for PieceWithAvailability {}
154
155impl PartialOrd for PieceWithAvailability {
156 fn partial_cmp(&self, other: &Self) -> Option<CmpOrdering> {
157 Some(self.cmp(other))
158 }
159}
160
161impl Ord for PieceWithAvailability {
162 fn cmp(&self, other: &Self) -> CmpOrdering {
163 self.availability
164 .cmp(&other.availability)
165 .then(self.piece_index.cmp(&other.piece_index))
166 }
167}
168
169struct AvailabilityIndex {
170 piece_to_availability: Vec<AtomicU32>,
171}
172
173impl AvailabilityIndex {
174 fn new(piece_count: usize) -> Self {
175 let mut piece_to_availability = Vec::with_capacity(piece_count);
176 for _ in 0..piece_count {
177 piece_to_availability.push(AtomicU32::new(0));
178 }
179 Self {
180 piece_to_availability,
181 }
182 }
183
184 fn get_availability(&self, piece_index: u32) -> u32 {
185 self.piece_to_availability
186 .get(piece_index as usize)
187 .map(|a| a.load(Ordering::Relaxed))
188 .unwrap_or(0)
189 }
190
191 fn increment(&self, piece_index: u32) -> (u32, u32) {
192 if let Some(atomic) = self.piece_to_availability.get(piece_index as usize) {
193 let old = atomic.fetch_add(1, Ordering::Relaxed);
194 (old, old + 1)
195 } else {
196 (0, 0)
197 }
198 }
199
200 fn decrement(&self, piece_index: u32) -> (u32, u32) {
201 if let Some(atomic) = self.piece_to_availability.get(piece_index as usize) {
202 loop {
203 let old = atomic.load(Ordering::Relaxed);
204 if old == 0 {
205 return (0, 0);
206 }
207 match atomic.compare_exchange_weak(
208 old,
209 old - 1,
210 Ordering::Relaxed,
211 Ordering::Relaxed,
212 ) {
213 Ok(_) => return (old, old - 1),
214 Err(_) => continue,
215 }
216 }
217 } else {
218 (0, 0)
219 }
220 }
221}
222
223struct DownloadablePieces {
224 candidates: BTreeSet<PieceWithAvailability>,
225 in_candidates: HashSet<u32>,
226}
227
228impl DownloadablePieces {
229 fn new() -> Self {
230 Self {
231 candidates: BTreeSet::new(),
232 in_candidates: HashSet::new(),
233 }
234 }
235
236 fn add(&mut self, piece_index: u32, availability: u32) {
237 if self.in_candidates.insert(piece_index) {
238 self.candidates.insert(PieceWithAvailability {
239 availability,
240 piece_index,
241 });
242 }
243 }
244
245 fn remove(&mut self, piece_index: u32, availability: u32) {
246 if self.in_candidates.remove(&piece_index) {
247 self.candidates.remove(&PieceWithAvailability {
248 availability,
249 piece_index,
250 });
251 }
252 }
253
254 fn update_availability(&mut self, piece_index: u32, old_avail: u32, new_avail: u32) {
255 if self.in_candidates.contains(&piece_index) {
256 self.candidates.remove(&PieceWithAvailability {
257 availability: old_avail,
258 piece_index,
259 });
260 self.candidates.insert(PieceWithAvailability {
261 availability: new_avail,
262 piece_index,
263 });
264 }
265 }
266}
267
268pub struct PieceManager {
287 piece_count: usize,
288 piece_length: u64,
289 total_length: u64,
290 our_bitfield: RwLock<Bitfield>,
291 active_pieces: RwLock<HashMap<u32, PieceState>>,
292 availability_index: AvailabilityIndex,
293 downloadable: RwLock<DownloadablePieces>,
294 completed_pieces: RwLock<HashSet<u32>>,
295 verified_pieces: RwLock<HashSet<u32>>,
296 verification_complete: AtomicBool,
297 verifying_pieces: RwLock<HashSet<u32>>,
298}
299
300impl PieceManager {
301 pub fn new(piece_count: usize, piece_length: u64, total_length: u64) -> Arc<Self> {
309 let mut downloadable = DownloadablePieces::new();
310 for i in 0..piece_count {
311 downloadable.add(i as u32, 0);
312 }
313 Arc::new(Self {
314 piece_count,
315 piece_length,
316 total_length,
317 our_bitfield: RwLock::new(Bitfield::new(piece_count)),
318 active_pieces: RwLock::new(HashMap::new()),
319 availability_index: AvailabilityIndex::new(piece_count),
320 downloadable: RwLock::new(downloadable),
321 completed_pieces: RwLock::new(HashSet::new()),
322 verified_pieces: RwLock::new(HashSet::new()),
323 verification_complete: AtomicBool::new(false),
324 verifying_pieces: RwLock::new(HashSet::new()),
325 })
326 }
327
328 pub fn bitfield(&self) -> Bitfield {
330 self.our_bitfield.read().clone()
331 }
332
333 pub fn is_complete(&self) -> bool {
335 self.our_bitfield.read().is_complete()
336 }
337
338 pub fn have_count(&self) -> usize {
340 self.our_bitfield.read().count()
341 }
342
343 pub fn active_piece_count(&self) -> usize {
345 self.active_pieces.read().len()
346 }
347
348 pub fn mark_piece_complete(&self, index: u32) {
350 let mut bf = self.our_bitfield.write();
351 bf.set_piece(index as usize);
352 self.completed_pieces.write().insert(index);
353 self.active_pieces.write().remove(&index);
354 self.verifying_pieces.write().remove(&index);
355 let avail = self.availability_index.get_availability(index);
356 self.downloadable.write().remove(index, avail);
357 }
358
359 pub fn mark_piece_failed(&self, index: u32) {
361 self.active_pieces.write().remove(&index);
362 self.verifying_pieces.write().remove(&index);
363 let avail = self.availability_index.get_availability(index);
364 self.downloadable.write().add(index, avail);
365 }
366
367 pub fn start_verifying(&self, index: u32) -> bool {
369 let mut verifying = self.verifying_pieces.write();
370 if verifying.contains(&index) {
371 false
372 } else {
373 verifying.insert(index);
374 true
375 }
376 }
377
378 pub fn finish_verifying(&self, index: u32) {
380 self.verifying_pieces.write().remove(&index);
381 }
382
383 pub fn mark_piece_verified(&self, index: u32) {
385 self.verified_pieces.write().insert(index);
386 }
387
388 pub fn mark_verification_complete(&self) {
390 self.verification_complete.store(true, Ordering::Release);
391 }
392
393 pub fn is_verification_complete(&self) -> bool {
395 self.verification_complete.load(Ordering::Acquire)
396 }
397
398 pub fn is_piece_verified(&self, index: u32) -> bool {
400 if self.verification_complete.load(Ordering::Acquire) {
401 return true;
402 }
403 self.verified_pieces.read().contains(&index)
404 }
405
406 pub fn verified_count(&self) -> usize {
408 if self.verification_complete.load(Ordering::Acquire) {
409 self.piece_count
410 } else {
411 self.verified_pieces.read().len()
412 }
413 }
414
415 pub fn update_availability(&self, peer_bitfield: &Bitfield) {
417 let mut downloadable = self.downloadable.write();
418 for i in 0..self.piece_count {
419 if peer_bitfield.has_piece(i) {
420 let (old_avail, new_avail) = self.availability_index.increment(i as u32);
421 downloadable.update_availability(i as u32, old_avail, new_avail);
422 }
423 }
424 }
425
426 pub fn decrement_availability(&self, peer_bitfield: &Bitfield) {
428 let mut downloadable = self.downloadable.write();
429 for i in 0..self.piece_count {
430 if peer_bitfield.has_piece(i) {
431 let (old_avail, new_avail) = self.availability_index.decrement(i as u32);
432 downloadable.update_availability(i as u32, old_avail, new_avail);
433 }
434 }
435 }
436
437 pub fn increment_piece_availability(&self, index: usize) {
439 if index < self.piece_count {
440 let (old_avail, new_avail) = self.availability_index.increment(index as u32);
441 self.downloadable
442 .write()
443 .update_availability(index as u32, old_avail, new_avail);
444 }
445 }
446
447 pub fn pick_piece(&self, peer_bitfield: &Bitfield) -> Option<u32> {
454 let have_count = self.have_count();
455 let active = self.active_pieces.read();
456 let downloadable = self.downloadable.read();
457
458 const COLD_START_THRESHOLD: usize = 4;
459 const RANDOM_POOL_SIZE: usize = 10;
460
461 if have_count < COLD_START_THRESHOLD {
462 let mut candidates: Vec<u32> = downloadable
463 .candidates
464 .iter()
465 .filter(|pwa| {
466 peer_bitfield.has_piece(pwa.piece_index as usize)
467 && !active.contains_key(&pwa.piece_index)
468 })
469 .take(RANDOM_POOL_SIZE)
470 .map(|pwa| pwa.piece_index)
471 .collect();
472
473 if !candidates.is_empty() {
474 let mut rng = rand::rng();
475 candidates.shuffle(&mut rng);
476 return candidates.first().copied();
477 }
478 }
479
480 for pwa in &downloadable.candidates {
482 let idx = pwa.piece_index;
483 if peer_bitfield.has_piece(idx as usize) && !active.contains_key(&idx) {
484 return Some(idx);
485 }
486 }
487
488 for pwa in &downloadable.candidates {
490 let idx = pwa.piece_index;
491 if peer_bitfield.has_piece(idx as usize) {
492 if let Some(state) = active.get(&idx) {
493 let piece_len = self.piece_size(idx) as u32;
494 let block_count = piece_len.div_ceil(BLOCK_SIZE);
495 let received_or_pending = state.blocks.len() + state.pending_blocks.len();
496 if (received_or_pending as u32) < block_count {
497 return Some(idx);
498 }
499 }
500 }
501 }
502
503 None
504 }
505
506 pub fn pick_piece_sequential(&self, peer_bitfield: &Bitfield) -> Option<u32> {
508 self.pick_piece_sequential_with_priorities(peer_bitfield, None)
509 }
510
511 pub fn pick_piece_sequential_with_priorities(
515 &self,
516 peer_bitfield: &Bitfield,
517 piece_priorities: Option<&[u8]>,
518 ) -> Option<u32> {
519 let our_bf = self.our_bitfield.read();
520 let active = self.active_pieces.read();
521
522 for i in 0..self.piece_count {
523 if let Some(priorities) = piece_priorities {
524 if i < priorities.len() && priorities[i] == 0 {
525 continue;
526 }
527 }
528
529 if !our_bf.has_piece(i)
530 && peer_bitfield.has_piece(i)
531 && !active.contains_key(&(i as u32))
532 {
533 return Some(i as u32);
534 }
535 }
536
537 for i in 0..self.piece_count {
539 if let Some(priorities) = piece_priorities {
540 if i < priorities.len() && priorities[i] == 0 {
541 continue;
542 }
543 }
544
545 if !our_bf.has_piece(i) && peer_bitfield.has_piece(i) {
546 if let Some(state) = active.get(&(i as u32)) {
547 let piece_len = self.piece_size(i as u32) as u32;
548 let block_count = piece_len.div_ceil(BLOCK_SIZE);
549 let received_or_pending = state.blocks.len() + state.pending_blocks.len();
550 if (received_or_pending as u32) < block_count {
551 return Some(i as u32);
552 }
553 }
554 }
555 }
556
557 None
558 }
559
560 pub fn pick_piece_with_priorities(
562 &self,
563 peer_bitfield: &Bitfield,
564 piece_priorities: Option<&[u8]>,
565 ) -> Option<u32> {
566 let have_count = self.have_count();
567 let active = self.active_pieces.read();
568 let downloadable = self.downloadable.read();
569
570 const COLD_START_THRESHOLD: usize = 4;
571 const RANDOM_POOL_SIZE: usize = 10;
572
573 if have_count < COLD_START_THRESHOLD {
574 let mut candidates: Vec<u32> = downloadable
575 .candidates
576 .iter()
577 .filter(|pwa| {
578 if let Some(priorities) = piece_priorities {
579 if (pwa.piece_index as usize) < priorities.len()
580 && priorities[pwa.piece_index as usize] == 0
581 {
582 return false;
583 }
584 }
585 peer_bitfield.has_piece(pwa.piece_index as usize)
586 && !active.contains_key(&pwa.piece_index)
587 })
588 .take(RANDOM_POOL_SIZE)
589 .map(|pwa| pwa.piece_index)
590 .collect();
591
592 if !candidates.is_empty() {
593 let mut rng = rand::rng();
594 candidates.shuffle(&mut rng);
595 return candidates.first().copied();
596 }
597 }
598
599 for pwa in &downloadable.candidates {
600 let idx = pwa.piece_index;
601
602 if let Some(priorities) = piece_priorities {
603 if (idx as usize) < priorities.len() && priorities[idx as usize] == 0 {
604 continue;
605 }
606 }
607
608 if peer_bitfield.has_piece(idx as usize) && !active.contains_key(&idx) {
609 return Some(idx);
610 }
611 }
612
613 for pwa in &downloadable.candidates {
614 let idx = pwa.piece_index;
615
616 if let Some(priorities) = piece_priorities {
617 if (idx as usize) < priorities.len() && priorities[idx as usize] == 0 {
618 continue;
619 }
620 }
621
622 if peer_bitfield.has_piece(idx as usize) {
623 if let Some(state) = active.get(&idx) {
624 let piece_len = self.piece_size(idx) as u32;
625 let block_count = piece_len.div_ceil(BLOCK_SIZE);
626 let received_or_pending = state.blocks.len() + state.pending_blocks.len();
627 if (received_or_pending as u32) < block_count {
628 return Some(idx);
629 }
630 }
631 }
632 }
633
634 None
635 }
636
637 pub fn get_block_requests(&self, piece_index: u32) -> Vec<BlockRequest> {
639 let piece_len = self.piece_size(piece_index);
640 let active = self.active_pieces.read();
641 let mut requests = Vec::new();
642
643 let state = active.get(&piece_index);
644
645 let mut offset = 0u32;
646 while offset < piece_len as u32 {
647 let length = std::cmp::min(BLOCK_SIZE, piece_len as u32 - offset);
648
649 let should_request = match state {
650 Some(s) => {
651 !s.blocks.contains_key(&offset) && !s.pending_blocks.contains_key(&offset)
652 }
653 None => true,
654 };
655
656 if should_request {
657 requests.push(BlockRequest {
658 piece_index,
659 offset,
660 length,
661 });
662 }
663 offset += length;
664 }
665
666 requests
667 }
668
669 pub fn start_piece(&self, piece_index: u32) {
671 let piece_len = self.piece_size(piece_index) as u32;
672 let mut active = self.active_pieces.write();
673 active
674 .entry(piece_index)
675 .or_insert_with(|| PieceState::new(piece_len));
676 }
677
678 pub fn add_pending_block(&self, request: &BlockRequest) {
680 let mut active = self.active_pieces.write();
681 if let Some(state) = active.get_mut(&request.piece_index) {
682 state.pending_blocks.insert(request.offset, Instant::now());
683 }
684 }
685
686 pub fn receive_block(&self, block: Block) -> Result<bool, PeerError> {
688 let mut active = self.active_pieces.write();
689
690 let state = active
691 .get_mut(&block.piece_index)
692 .ok_or(PeerError::InvalidPieceIndex(block.piece_index))?;
693
694 state.pending_blocks.remove(&block.offset);
695 state.blocks.insert(block.offset, block.data);
696
697 Ok(state.is_complete())
698 }
699
700 pub fn cancel_piece(&self, piece_index: u32) {
702 self.active_pieces.write().remove(&piece_index);
703 }
704
705 pub fn get_stale_pieces(&self) -> Vec<u32> {
707 let active = self.active_pieces.read();
708 active
709 .iter()
710 .filter(|(_, state)| !state.expired_requests().is_empty())
711 .map(|(&idx, _)| idx)
712 .collect()
713 }
714
715 pub fn cleanup_stale_pieces(&self) -> Vec<u32> {
717 let stale = self.get_stale_pieces();
718 let mut active = self.active_pieces.write();
719 for &idx in &stale {
720 active.remove(&idx);
721 }
722 stale
723 }
724
725 pub fn assemble_piece(&self, piece_index: u32) -> Option<Bytes> {
727 let active = self.active_pieces.read();
728 active.get(&piece_index).map(|state| state.assemble())
729 }
730
731 pub fn piece_size(&self, index: u32) -> u64 {
733 if self.piece_count == 0 {
734 return 0;
735 }
736 if (index as usize) < self.piece_count - 1 {
737 self.piece_length
738 } else {
739 let remainder = self.total_length % self.piece_length;
740 if remainder == 0 {
741 self.piece_length
742 } else {
743 remainder
744 }
745 }
746 }
747
748 pub fn get_endgame_requests(&self) -> Vec<BlockRequest> {
750 let active = self.active_pieces.read();
751 let mut requests = Vec::new();
752
753 for (&piece_index, state) in active.iter() {
754 for &offset in state.pending_blocks.keys() {
755 let remaining = state.piece_length - offset;
756 let length = std::cmp::min(BLOCK_SIZE, remaining);
757 requests.push(BlockRequest {
758 piece_index,
759 offset,
760 length,
761 });
762 }
763 }
764
765 requests
766 }
767
768 pub fn is_endgame(&self) -> bool {
770 let remaining = self.piece_count - self.have_count();
771 remaining <= 10 && remaining > 0
772 }
773
774 pub fn cancel_block(&self, request: &BlockRequest) {
776 let mut active = self.active_pieces.write();
777 if let Some(state) = active.get_mut(&request.piece_index) {
778 state.pending_blocks.remove(&request.offset);
779 }
780 }
781}