3554 lines
137 KiB
Zig
3554 lines
137 KiB
Zig
//! Download management and piece selection
|
|
//!
|
|
//! This module handles download operations, piece request management,
|
|
//! peer coordination, and download progress tracking.
|
|
|
|
const std = @import("std");
|
|
const testing = std.testing;
|
|
const mem = std.mem;
|
|
const atomic = std.atomic;
|
|
const fmt = std.fmt;
|
|
|
|
const core = @import("core");
|
|
const Error = core.errors.Error;
|
|
const hash = @import("hash.zig");
|
|
const PieceHash = hash.PieceHash;
|
|
const HashUtils = hash.HashUtils;
|
|
const file = @import("file.zig");
|
|
const FileChunker = file.FileChunker;
|
|
const FileWriter = file.FileWriter;
|
|
const piece = @import("piece.zig");
|
|
const PieceSelector = piece.PieceSelector;
|
|
const SelectionStrategy = piece.SelectionStrategy;
|
|
const PieceAvailability = piece.PieceAvailability;
|
|
const path_security = @import("path_security.zig");
|
|
const PathValidator = path_security.PathValidator;
|
|
const peer_metrics = @import("peer_metrics.zig");
|
|
const PeerMetrics = peer_metrics.PeerMetrics;
|
|
const PeerMetricsManager = peer_metrics.PeerMetricsManager;
|
|
|
|
/// Download request structure
|
|
/// MEM-M5 FIX: Use fixed-size array for peer_id to avoid dangling pointer
|
|
/// Peer IDs are always 32 bytes, so we copy into owned storage
|
|
pub const DownloadRequest = struct {
|
|
piece_index: u32,
|
|
offset: u64,
|
|
length: u32,
|
|
priority: PieceAvailability.Priority,
|
|
requested_at: i64,
|
|
// MEM-M5 FIX: Fixed-size array instead of slice to prevent dangling pointer
|
|
peer_id: [32]u8,
|
|
|
|
/// Create download request
|
|
/// MEM-M5 FIX: Copies peer_id into owned storage
|
|
/// MEM-M3 FIX: Validates offset + length doesn't overflow
|
|
pub fn create(
|
|
piece_index: u32,
|
|
offset: u64,
|
|
length: u32,
|
|
priority: PieceAvailability.Priority,
|
|
peer_id: []const u8,
|
|
) ?DownloadRequest {
|
|
// MEM-M3 FIX: Check for offset + length overflow
|
|
const end_offset = std.math.add(u64, offset, length) catch {
|
|
std.log.warn("MEM-M3: Download request overflow: offset={} + length={}", .{ offset, length });
|
|
return null;
|
|
};
|
|
|
|
// MEM-M3 FIX: Sanity check on length (max piece size from centralized config)
|
|
// MED-12 FIX: Use centralized limits
|
|
const max_piece = core.limits.global.file.max_piece_size;
|
|
const max_piece_u32: u32 = if (max_piece > std.math.maxInt(u32)) std.math.maxInt(u32) else @intCast(max_piece);
|
|
if (length > max_piece_u32) {
|
|
std.log.warn("MEM-M3: Download request length too large: {}", .{length});
|
|
return null;
|
|
}
|
|
|
|
_ = end_offset; // Used for overflow check
|
|
|
|
var owned_peer_id: [32]u8 = [_]u8{0} ** 32;
|
|
const copy_len = @min(peer_id.len, 32);
|
|
@memcpy(owned_peer_id[0..copy_len], peer_id[0..copy_len]);
|
|
|
|
return DownloadRequest{
|
|
.piece_index = piece_index,
|
|
.offset = offset,
|
|
.length = length,
|
|
.priority = priority,
|
|
.requested_at = std.time.timestamp(),
|
|
.peer_id = owned_peer_id,
|
|
};
|
|
}
|
|
|
|
/// Get peer ID as slice for compatibility
|
|
pub fn getPeerId(self: *const DownloadRequest) []const u8 {
|
|
return &self.peer_id;
|
|
}
|
|
|
|
/// Check if request has expired
|
|
pub fn isExpired(self: DownloadRequest, timeout_seconds: i64) bool {
|
|
return std.time.timestamp() - self.requested_at > timeout_seconds;
|
|
}
|
|
};
|
|
|
|
/// Download state tracking
|
|
///
|
|
/// NOTE: This struct uses separate atomic operations for different metrics.
|
|
/// While individual atomics are thread-safe, operations that update multiple
|
|
/// fields are NOT atomic as a group. This means:
|
|
/// - downloaded_bytes and verified_bytes may be momentarily inconsistent
|
|
/// - completed_pieces + failed_pieces may not sum to expected totals at all times
|
|
///
|
|
/// This is acceptable for statistics tracking where eventual consistency is
|
|
/// sufficient. If strict transactional semantics are needed, use a mutex.
|
|
pub const DownloadState = struct {
|
|
total_size: u64,
|
|
downloaded_bytes: atomic.Value(u64),
|
|
verified_bytes: atomic.Value(u64),
|
|
piece_count: u32,
|
|
completed_pieces: atomic.Value(u32),
|
|
failed_pieces: atomic.Value(u32),
|
|
start_time: i64,
|
|
|
|
pub fn init(total_size: u64, piece_count: u32) DownloadState {
|
|
return DownloadState{
|
|
.total_size = total_size,
|
|
.downloaded_bytes = atomic.Value(u64).init(0),
|
|
.verified_bytes = atomic.Value(u64).init(0),
|
|
.piece_count = piece_count,
|
|
.completed_pieces = atomic.Value(u32).init(0),
|
|
.failed_pieces = atomic.Value(u32).init(0),
|
|
.start_time = std.time.timestamp(),
|
|
};
|
|
}
|
|
|
|
/// Update downloaded bytes
|
|
///
|
|
/// HIGH-4 FIX: Thread-safe atomic operation with release ordering
|
|
/// to ensure writes are visible to other threads promptly.
|
|
pub fn addDownloadedBytes(self: *DownloadState, bytes: u64) void {
|
|
_ = self.downloaded_bytes.fetchAdd(bytes, .release);
|
|
}
|
|
|
|
/// Update verified bytes
|
|
///
|
|
/// HIGH-4 FIX: Thread-safe atomic operation with release ordering.
|
|
pub fn addVerifiedBytes(self: *DownloadState, bytes: u64) void {
|
|
_ = self.verified_bytes.fetchAdd(bytes, .release);
|
|
}
|
|
|
|
/// Mark piece as completed
|
|
///
|
|
/// HIGH-4 FIX: Thread-safe atomic operation with release ordering.
|
|
pub fn markPieceCompleted(self: *DownloadState) void {
|
|
_ = self.completed_pieces.fetchAdd(1, .release);
|
|
}
|
|
|
|
/// Mark piece as failed
|
|
///
|
|
/// HIGH-4 FIX: Thread-safe atomic operation with release ordering.
|
|
pub fn markPieceFailed(self: *DownloadState) void {
|
|
_ = self.failed_pieces.fetchAdd(1, .release);
|
|
}
|
|
|
|
/// Get download progress (0.0 to 1.0)
|
|
/// HIGH-4 FIX: Uses acquire ordering to see latest writes.
|
|
pub fn getProgress(self: *DownloadState) f32 {
|
|
if (self.total_size == 0) return 0.0;
|
|
const downloaded = self.downloaded_bytes.load(.acquire);
|
|
return @as(f32, @floatFromInt(downloaded)) / @as(f32, @floatFromInt(self.total_size));
|
|
}
|
|
|
|
/// Get verification progress (0.0 to 1.0)
|
|
/// HIGH-4 FIX: Uses acquire ordering to see latest writes.
|
|
pub fn getVerificationProgress(self: *DownloadState) f32 {
|
|
if (self.total_size == 0) return 0.0;
|
|
const verified = self.verified_bytes.load(.acquire);
|
|
return @as(f32, @floatFromInt(verified)) / @as(f32, @floatFromInt(self.total_size));
|
|
}
|
|
|
|
/// Get download speed (bytes per second)
|
|
/// HIGH-4 FIX: Uses acquire ordering to see latest writes.
|
|
pub fn getDownloadSpeed(self: *DownloadState) f32 {
|
|
const elapsed = std.time.timestamp() - self.start_time;
|
|
if (elapsed <= 0) return 0.0;
|
|
|
|
const downloaded = self.downloaded_bytes.load(.acquire);
|
|
return @as(f32, @floatFromInt(downloaded)) / @as(f32, @floatFromInt(elapsed));
|
|
}
|
|
|
|
/// HIGH-4 FIX: Get a consistent snapshot of completion statistics.
|
|
/// This reads all piece-related counters with acquire semantics
|
|
/// and returns them as a struct for consistent progress reporting.
|
|
pub const CompletionStats = struct {
|
|
completed: u32,
|
|
failed: u32,
|
|
total: u32,
|
|
};
|
|
|
|
pub fn getCompletionStats(self: *DownloadState) CompletionStats {
|
|
return .{
|
|
.completed = self.completed_pieces.load(.acquire),
|
|
.failed = self.failed_pieces.load(.acquire),
|
|
.total = self.piece_count,
|
|
};
|
|
}
|
|
|
|
/// Get estimated time remaining
|
|
pub fn getTimeRemaining(self: *DownloadState) i64 {
|
|
// Check completion first - if done, time remaining is 0
|
|
const downloaded = self.downloaded_bytes.load(.monotonic);
|
|
if (downloaded >= self.total_size) return 0;
|
|
|
|
const speed = self.getDownloadSpeed();
|
|
if (speed <= 0.0) return -1;
|
|
|
|
const remaining_bytes = self.total_size - downloaded;
|
|
const seconds_remaining = @as(i64, @intFromFloat(@as(f32, @floatFromInt(remaining_bytes)) / speed));
|
|
|
|
return seconds_remaining;
|
|
}
|
|
|
|
/// Check if download is complete
|
|
pub fn isComplete(self: *const DownloadState) bool {
|
|
return self.completed_pieces.load(.acquire) == self.piece_count;
|
|
}
|
|
|
|
/// Get completion percentage
|
|
pub fn getCompletionPercent(self: *DownloadState) f32 {
|
|
if (self.piece_count == 0) return 0.0;
|
|
return @as(f32, @floatFromInt(self.completed_pieces.load(.monotonic))) / @as(f32, @floatFromInt(self.piece_count)) * 100.0;
|
|
}
|
|
};
|
|
|
|
/// Per-peer piece availability tracking
|
|
/// IMP-M1 FIX: Track which peers have which pieces for intelligent peer selection
|
|
pub const PeerPieceMap = struct {
|
|
/// Maps peer_id (32 bytes) to set of piece indices they have
|
|
peer_pieces: std.AutoHashMap([32]u8, std.AutoHashMap(u32, void)),
|
|
/// Maps piece_index to set of peer_ids that have it
|
|
piece_peers: std.AutoHashMap(u32, std.AutoHashMap([32]u8, void)),
|
|
allocator: mem.Allocator,
|
|
|
|
pub fn init(allocator: mem.Allocator) PeerPieceMap {
|
|
return .{
|
|
.peer_pieces = std.AutoHashMap([32]u8, std.AutoHashMap(u32, void)).init(allocator),
|
|
.piece_peers = std.AutoHashMap(u32, std.AutoHashMap([32]u8, void)).init(allocator),
|
|
.allocator = allocator,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *PeerPieceMap) void {
|
|
// Free inner maps for peer_pieces
|
|
var peer_iter = self.peer_pieces.iterator();
|
|
while (peer_iter.next()) |entry| {
|
|
entry.value_ptr.deinit();
|
|
}
|
|
self.peer_pieces.deinit();
|
|
|
|
// Free inner maps for piece_peers
|
|
var piece_iter = self.piece_peers.iterator();
|
|
while (piece_iter.next()) |entry| {
|
|
entry.value_ptr.deinit();
|
|
}
|
|
self.piece_peers.deinit();
|
|
}
|
|
|
|
/// Record that a peer has a specific piece
|
|
pub fn addPeerPiece(self: *PeerPieceMap, peer_id: [32]u8, piece_index: u32) Error!void {
|
|
// Add to peer_pieces map
|
|
const peer_gop = try self.peer_pieces.getOrPut(peer_id);
|
|
if (!peer_gop.found_existing) {
|
|
peer_gop.value_ptr.* = std.AutoHashMap(u32, void).init(self.allocator);
|
|
}
|
|
try peer_gop.value_ptr.put(piece_index, {});
|
|
|
|
// Add to piece_peers map
|
|
const piece_gop = try self.piece_peers.getOrPut(piece_index);
|
|
if (!piece_gop.found_existing) {
|
|
piece_gop.value_ptr.* = std.AutoHashMap([32]u8, void).init(self.allocator);
|
|
}
|
|
try piece_gop.value_ptr.put(peer_id, {});
|
|
}
|
|
|
|
/// Record that a peer no longer has a specific piece
|
|
pub fn removePeerPiece(self: *PeerPieceMap, peer_id: [32]u8, piece_index: u32) void {
|
|
// Remove from peer_pieces
|
|
if (self.peer_pieces.getPtr(peer_id)) |pieces| {
|
|
_ = pieces.remove(piece_index);
|
|
}
|
|
|
|
// Remove from piece_peers
|
|
if (self.piece_peers.getPtr(piece_index)) |peers| {
|
|
_ = peers.remove(peer_id);
|
|
}
|
|
}
|
|
|
|
/// Remove a peer entirely (when they disconnect)
|
|
pub fn removePeer(self: *PeerPieceMap, peer_id: [32]u8) void {
|
|
// Get all pieces this peer had
|
|
if (self.peer_pieces.fetchRemove(peer_id)) |entry| {
|
|
// Remove peer from piece_peers for each piece
|
|
var pieces_iter = entry.value.iterator();
|
|
while (pieces_iter.next()) |piece_entry| {
|
|
if (self.piece_peers.getPtr(piece_entry.key_ptr.*)) |peers| {
|
|
_ = peers.remove(peer_id);
|
|
}
|
|
}
|
|
// Free the inner map
|
|
var inner = entry.value;
|
|
inner.deinit();
|
|
}
|
|
}
|
|
|
|
/// Get peers that have a specific piece
|
|
pub fn getPeersForPiece(self: *PeerPieceMap, piece_index: u32) ?*std.AutoHashMap([32]u8, void) {
|
|
return self.piece_peers.getPtr(piece_index);
|
|
}
|
|
|
|
/// Check if a peer has a specific piece
|
|
pub fn peerHasPiece(self: *PeerPieceMap, peer_id: [32]u8, piece_index: u32) bool {
|
|
if (self.peer_pieces.get(peer_id)) |pieces| {
|
|
return pieces.contains(piece_index);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// Get count of peers that have a piece
|
|
pub fn getPeerCountForPiece(self: *PeerPieceMap, piece_index: u32) usize {
|
|
if (self.piece_peers.get(piece_index)) |peers| {
|
|
return peers.count();
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/// Get count of pieces a peer has
|
|
pub fn getPieceCountForPeer(self: *PeerPieceMap, peer_id: [32]u8) usize {
|
|
if (self.peer_pieces.get(peer_id)) |pieces| {
|
|
return pieces.count();
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/// Get all known peers (returns a key iterator over peer_pieces)
|
|
/// CASCADE FIX: Enables broadcasting "have" messages to all connected peers
|
|
pub fn getAllPeers(self: *PeerPieceMap) std.AutoHashMap([32]u8, std.AutoHashMap(u32, void)).KeyIterator {
|
|
return self.peer_pieces.keyIterator();
|
|
}
|
|
|
|
/// Get count of all known peers
|
|
pub fn getPeerCount(self: *PeerPieceMap) usize {
|
|
return self.peer_pieces.count();
|
|
}
|
|
};
|
|
|
|
/// Per-peer in-flight request tracking for request pipelining
|
|
/// PERF: Tracks outstanding requests per peer to enable pipelining multiple requests
|
|
/// instead of waiting for each response before sending the next request.
|
|
/// ADAPTIVE: Uses BDP-based metrics for dynamic queue depth per peer.
|
|
pub const PeerRequestTracker = struct {
|
|
/// Maps peer_id to set of piece indices currently requested from that peer
|
|
in_flight_pieces: std.AutoHashMap([32]u8, std.AutoHashMap(u32, void)),
|
|
/// Per-peer metrics for adaptive queue depth (RTT, bandwidth, BDP)
|
|
metrics_manager: PeerMetricsManager,
|
|
/// Default/fallback maximum requests per peer
|
|
default_max_requests: u32,
|
|
/// Piece size for BDP calculations
|
|
piece_size: u64,
|
|
allocator: mem.Allocator,
|
|
|
|
pub fn init(allocator: mem.Allocator, max_requests_per_peer: u32, piece_size: u64) PeerRequestTracker {
|
|
return .{
|
|
.in_flight_pieces = std.AutoHashMap([32]u8, std.AutoHashMap(u32, void)).init(allocator),
|
|
.metrics_manager = PeerMetricsManager.init(allocator, piece_size),
|
|
.default_max_requests = max_requests_per_peer,
|
|
.piece_size = piece_size,
|
|
.allocator = allocator,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *PeerRequestTracker) void {
|
|
// Free inner maps
|
|
var iter = self.in_flight_pieces.iterator();
|
|
while (iter.next()) |entry| {
|
|
entry.value_ptr.deinit();
|
|
}
|
|
self.in_flight_pieces.deinit();
|
|
self.metrics_manager.deinit();
|
|
}
|
|
|
|
/// Check if we can send another request to this peer (uses adaptive queue depth)
|
|
pub fn canRequestFromPeer(self: *PeerRequestTracker, peer_id: [32]u8) bool {
|
|
if (self.metrics_manager.get(peer_id)) |metrics| {
|
|
return metrics.canSendRequest();
|
|
}
|
|
// Fallback to default for unknown peers
|
|
const count = self.getInFlightCount(peer_id);
|
|
return count < self.default_max_requests;
|
|
}
|
|
|
|
/// Get available slots for this peer (uses adaptive queue depth)
|
|
pub fn getAvailableSlots(self: *PeerRequestTracker, peer_id: [32]u8) u32 {
|
|
if (self.metrics_manager.get(peer_id)) |metrics| {
|
|
return metrics.getAvailableSlots();
|
|
}
|
|
// Fallback to default
|
|
const count = self.getInFlightCount(peer_id);
|
|
if (count >= self.default_max_requests) return 0;
|
|
return self.default_max_requests - count;
|
|
}
|
|
|
|
/// Record that a request was sent to a peer
|
|
pub fn recordRequest(self: *PeerRequestTracker, peer_id: [32]u8, piece_index: u32) Error!void {
|
|
// Track in metrics (creates entry if needed)
|
|
const metrics = try self.metrics_manager.getOrCreate(peer_id);
|
|
metrics.recordRequestSent();
|
|
|
|
// Track piece
|
|
const pieces_gop = try self.in_flight_pieces.getOrPut(peer_id);
|
|
if (!pieces_gop.found_existing) {
|
|
pieces_gop.value_ptr.* = std.AutoHashMap(u32, void).init(self.allocator);
|
|
}
|
|
try pieces_gop.value_ptr.put(piece_index, {});
|
|
}
|
|
|
|
/// Record that a request completed (success or failure)
|
|
pub fn recordCompletion(self: *PeerRequestTracker, peer_id: [32]u8, piece_index: u32) void {
|
|
self.recordCompletionWithSize(peer_id, piece_index, self.piece_size, true);
|
|
}
|
|
|
|
/// Record completion with actual bytes received and success/failure status
|
|
pub fn recordCompletionWithSize(self: *PeerRequestTracker, peer_id: [32]u8, piece_index: u32, bytes: u64, success: bool) void {
|
|
// Update metrics
|
|
if (self.metrics_manager.get(peer_id)) |metrics| {
|
|
metrics.recordResponseReceived(bytes, success);
|
|
}
|
|
|
|
// Remove from tracked pieces
|
|
if (self.in_flight_pieces.getPtr(peer_id)) |pieces| {
|
|
_ = pieces.remove(piece_index);
|
|
}
|
|
}
|
|
|
|
/// Check if a piece is already being requested from a peer
|
|
pub fn isPieceInFlight(self: *PeerRequestTracker, peer_id: [32]u8, piece_index: u32) bool {
|
|
if (self.in_flight_pieces.get(peer_id)) |pieces| {
|
|
return pieces.contains(piece_index);
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// Check if a piece is in flight to ANY peer
|
|
pub fn isPieceInFlightToAny(self: *PeerRequestTracker, piece_index: u32) bool {
|
|
var iter = self.in_flight_pieces.iterator();
|
|
while (iter.next()) |entry| {
|
|
if (entry.value_ptr.contains(piece_index)) {
|
|
return true;
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// Get current in-flight count for a peer
|
|
pub fn getInFlightCount(self: *PeerRequestTracker, peer_id: [32]u8) u32 {
|
|
if (self.metrics_manager.get(peer_id)) |metrics| {
|
|
return metrics.current_pending;
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
/// Get total in-flight requests across all peers
|
|
pub fn getTotalInFlight(self: *PeerRequestTracker) u32 {
|
|
return self.metrics_manager.getTotalPending();
|
|
}
|
|
|
|
/// Remove a peer entirely (when they disconnect)
|
|
pub fn removePeer(self: *PeerRequestTracker, peer_id: [32]u8) void {
|
|
self.metrics_manager.remove(peer_id);
|
|
if (self.in_flight_pieces.fetchRemove(peer_id)) |entry| {
|
|
var inner = entry.value;
|
|
inner.deinit();
|
|
}
|
|
}
|
|
|
|
/// Get the best peer for the next piece (based on score)
|
|
pub fn getBestPeer(self: *PeerRequestTracker, available_peers: []const [32]u8) ?[32]u8 {
|
|
return self.metrics_manager.getBestPeer(available_peers);
|
|
}
|
|
|
|
/// Get per-peer metrics for a peer
|
|
pub fn getPeerMetrics(self: *PeerRequestTracker, peer_id: [32]u8) ?*PeerMetrics {
|
|
return self.metrics_manager.get(peer_id);
|
|
}
|
|
|
|
/// Get aggregated metrics stats
|
|
pub fn getMetricsStats(self: *PeerRequestTracker) peer_metrics.MetricsStats {
|
|
return self.metrics_manager.getStats();
|
|
}
|
|
};
|
|
|
|
/// Download manager for coordinating downloads
|
|
///
|
|
/// THREAD SAFETY:
|
|
/// - All access to hashmaps (pending_requests, active_downloads, retry_trackers,
|
|
/// peer_piece_map) is protected by the manager_mutex.
|
|
/// - The DownloadState struct uses atomic.Value types for all mutable statistics
|
|
/// (downloaded_bytes, verified_bytes, completed_pieces, failed_pieces), making
|
|
/// stat updates thread-safe without mutex overhead.
|
|
/// - THR-CRIT-3 VERIFIED: Atomic operations use .monotonic ordering which is
|
|
/// sufficient for statistics counters (eventual consistency is acceptable).
|
|
pub const DownloadManager = struct {
|
|
/// Download progress statistics (uses atomic fields for thread-safety)
|
|
state: DownloadState,
|
|
selector: PieceSelector,
|
|
file_writer: ?FileWriter,
|
|
pending_requests: std.ArrayList(DownloadRequest),
|
|
active_downloads: std.AutoHashMap(u32, ActiveDownload),
|
|
retry_trackers: std.AutoHashMap(u32, PieceRetryTracker),
|
|
/// IMP-M1 FIX: Per-peer piece availability tracking
|
|
peer_piece_map: PeerPieceMap,
|
|
/// PERF: Per-peer in-flight request tracking for pipelining
|
|
request_tracker: PeerRequestTracker,
|
|
allocator: mem.Allocator,
|
|
piece_size: u64,
|
|
total_size: u64,
|
|
file_path: ?[]const u8,
|
|
request_timeout: i64,
|
|
/// Mutex protecting all hashmaps and lists
|
|
manager_mutex: std.Thread.Mutex = .{},
|
|
|
|
/// ADAPTIVE: Count of stuck downloads cleaned up since last query
|
|
/// Used by adaptive concurrency controller to detect network issues
|
|
stuck_downloads_cleaned: atomic.Value(u32) = atomic.Value(u32).init(0),
|
|
|
|
// PERF: Endgame mode - request remaining pieces from ALL peers
|
|
/// Whether endgame mode is active (last few pieces)
|
|
endgame_active: bool = false,
|
|
/// Threshold to enter endgame (0.95 = 95% complete)
|
|
endgame_threshold: f32 = 0.95,
|
|
/// Track which peers have been sent requests for each endgame piece
|
|
endgame_requests: std.AutoHashMap(u32, std.ArrayList([32]u8)) = undefined,
|
|
/// Whether endgame_requests has been initialized
|
|
endgame_initialized: bool = false,
|
|
/// PHASE 5: Flag indicating broadcast is needed (set when endgame first activates)
|
|
endgame_broadcast_pending: bool = false,
|
|
|
|
pub fn init(
|
|
total_size: u64,
|
|
piece_count: u32,
|
|
strategy: SelectionStrategy,
|
|
piece_size: u64,
|
|
allocator: mem.Allocator,
|
|
) Error!DownloadManager {
|
|
const seed = std.crypto.random.int(u64);
|
|
const selector = PieceSelector.init(strategy, seed, allocator);
|
|
|
|
return DownloadManager{
|
|
.state = DownloadState.init(total_size, piece_count),
|
|
.selector = selector,
|
|
.file_writer = null,
|
|
.pending_requests = .{},
|
|
.active_downloads = std.AutoHashMap(u32, ActiveDownload).init(allocator),
|
|
.retry_trackers = std.AutoHashMap(u32, PieceRetryTracker).init(allocator),
|
|
// IMP-M1 FIX: Initialize per-peer piece tracking
|
|
.peer_piece_map = PeerPieceMap.init(allocator),
|
|
// PERF: Initialize per-peer request tracking for pipelining with adaptive BDP
|
|
// Default queue depth used as fallback; actual depth calculated from RTT/bandwidth
|
|
.request_tracker = PeerRequestTracker.init(allocator, @intCast(core.limits.defaults.file.request_queue_depth), piece_size),
|
|
.allocator = allocator,
|
|
.piece_size = piece_size,
|
|
.total_size = total_size,
|
|
.file_path = null,
|
|
.request_timeout = 30, // 30 second timeout
|
|
// PERF: Endgame mode tracking
|
|
.endgame_requests = std.AutoHashMap(u32, std.ArrayList([32]u8)).init(allocator),
|
|
.endgame_initialized = true,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *DownloadManager) void {
|
|
self.pending_requests.deinit(self.allocator);
|
|
self.active_downloads.deinit();
|
|
self.retry_trackers.deinit();
|
|
// IMP-M1 FIX: Deinit per-peer piece tracking
|
|
self.peer_piece_map.deinit();
|
|
// PERF: Deinit per-peer request tracking
|
|
self.request_tracker.deinit();
|
|
self.selector.deinit();
|
|
if (self.file_writer) |*writer| {
|
|
writer.deinit();
|
|
}
|
|
// Free owned file_path copy
|
|
if (self.file_path) |path| {
|
|
self.allocator.free(path);
|
|
}
|
|
// PERF: Clean up endgame tracking
|
|
if (self.endgame_initialized) {
|
|
var it = self.endgame_requests.iterator();
|
|
while (it.next()) |entry| {
|
|
entry.value_ptr.deinit(self.allocator);
|
|
}
|
|
self.endgame_requests.deinit();
|
|
}
|
|
}
|
|
|
|
/// Set output file for download
|
|
pub fn setOutputFile(self: *DownloadManager, file_path: []const u8) Error!void {
|
|
// SECURITY: Validate path before creating file writer
|
|
// This is a basic validation - full validation should be done by the caller
|
|
// (FileSharingManager) using PathValidator.validateWritable()
|
|
if (!path_security.PathValidator.isPathSafe(file_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// FIX: Make a copy of the path FIRST to avoid use-after-free
|
|
// Both self.file_path and FileWriter need to point to owned memory
|
|
const path_copy = self.allocator.dupe(u8, file_path) catch return Error.OutOfMemory;
|
|
errdefer self.allocator.free(path_copy);
|
|
|
|
if (self.file_writer) |*writer| {
|
|
writer.deinit();
|
|
}
|
|
if (self.file_path) |old_path| {
|
|
self.allocator.free(old_path);
|
|
}
|
|
|
|
// Use the copy for FileWriter so it points to owned memory
|
|
self.file_writer = try FileWriter.init(path_copy, self.allocator, self.total_size);
|
|
self.file_path = path_copy;
|
|
}
|
|
|
|
/// Set output file for resume - opens existing file without truncating
|
|
pub fn setOutputFileForResume(self: *DownloadManager, file_path: []const u8) Error!void {
|
|
// SECURITY: Validate path before opening file
|
|
if (!path_security.PathValidator.isPathSafe(file_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// Make a copy of the path to avoid use-after-free
|
|
const path_copy = self.allocator.dupe(u8, file_path) catch return Error.OutOfMemory;
|
|
errdefer self.allocator.free(path_copy);
|
|
|
|
if (self.file_writer) |*writer| {
|
|
writer.deinit();
|
|
}
|
|
if (self.file_path) |old_path| {
|
|
self.allocator.free(old_path);
|
|
}
|
|
|
|
// Use initForResume to preserve existing file content
|
|
self.file_writer = try FileWriter.initForResume(path_copy, self.allocator);
|
|
self.file_path = path_copy;
|
|
}
|
|
|
|
/// Add peer with piece availability
|
|
/// IMP-M1 FIX: Now tracks which peer has which pieces
|
|
pub fn addPeer(self: *DownloadManager, peer_id: []const u8, available_pieces: []const u32) Error!void {
|
|
// Convert peer_id to fixed-size array
|
|
var peer_id_array: [32]u8 = [_]u8{0} ** 32;
|
|
const copy_len = @min(peer_id.len, 32);
|
|
@memcpy(peer_id_array[0..copy_len], peer_id[0..copy_len]);
|
|
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// Create a set of available pieces for fast lookup
|
|
var piece_set = std.AutoHashMap(u32, void).init(self.allocator);
|
|
defer piece_set.deinit();
|
|
|
|
for (available_pieces) |piece_index| {
|
|
// IMP-M1 FIX: Track this peer has this piece
|
|
try self.peer_piece_map.addPeerPiece(peer_id_array, piece_index);
|
|
|
|
// Update selector availability count based on actual peer count
|
|
// FIX: Use updateAvailability instead of addPiece to preserve
|
|
// is_downloaded/is_verified state. addPiece replaces the entry entirely,
|
|
// wiping verification state and causing COMPLETION MISMATCH oscillation.
|
|
const peer_count = self.peer_piece_map.getPeerCountForPiece(piece_index);
|
|
try self.selector.updateAvailability(piece_index, @intCast(peer_count));
|
|
try self.selector.setPriority(piece_index, .normal);
|
|
|
|
// Track for pending request update
|
|
piece_set.put(piece_index, {}) catch {};
|
|
}
|
|
|
|
// STUCK FIX: Update pending requests that have zero peer_id with this new peer
|
|
// This handles the case where requests were queued but had no peer available
|
|
const zero_peer: [32]u8 = [_]u8{0} ** 32;
|
|
for (self.pending_requests.items) |*request| {
|
|
if (std.mem.eql(u8, &request.peer_id, &zero_peer)) {
|
|
if (piece_set.contains(request.piece_index)) {
|
|
request.peer_id = peer_id_array;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Update peer piece availability
|
|
/// IMP-M1 FIX: Now properly tracks per-peer piece availability
|
|
pub fn updatePeerAvailability(self: *DownloadManager, peer_id: []const u8, piece_index: u32, is_available: bool) Error!void {
|
|
// Convert peer_id to fixed-size array
|
|
var peer_id_array: [32]u8 = [_]u8{0} ** 32;
|
|
const copy_len = @min(peer_id.len, 32);
|
|
@memcpy(peer_id_array[0..copy_len], peer_id[0..copy_len]);
|
|
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
if (is_available) {
|
|
// IMP-M1 FIX: Track that this peer now has this piece
|
|
try self.peer_piece_map.addPeerPiece(peer_id_array, piece_index);
|
|
} else {
|
|
// IMP-M1 FIX: Track that this peer no longer has this piece
|
|
self.peer_piece_map.removePeerPiece(peer_id_array, piece_index);
|
|
}
|
|
|
|
// Update selector availability count based on actual peer count
|
|
const peer_count = self.peer_piece_map.getPeerCountForPiece(piece_index);
|
|
try self.selector.updateAvailability(piece_index, @intCast(peer_count));
|
|
}
|
|
|
|
/// Remove a peer entirely (when they disconnect)
|
|
/// IMP-M1 FIX: Cleans up all piece tracking for this peer
|
|
pub fn removePeer(self: *DownloadManager, peer_id: []const u8) void {
|
|
// Convert peer_id to fixed-size array
|
|
var peer_id_array: [32]u8 = [_]u8{0} ** 32;
|
|
const copy_len = @min(peer_id.len, 32);
|
|
@memcpy(peer_id_array[0..copy_len], peer_id[0..copy_len]);
|
|
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// IMP-M1 FIX: Remove this peer from tracking and update availability counts
|
|
// Get pieces this peer had before removing
|
|
if (self.peer_piece_map.peer_pieces.get(peer_id_array)) |pieces| {
|
|
// Update availability for each piece this peer had
|
|
var iter = pieces.iterator();
|
|
var update_failures: u32 = 0;
|
|
while (iter.next()) |entry| {
|
|
const piece_index = entry.key_ptr.*;
|
|
// After removal, update selector with new peer count
|
|
const new_count = self.peer_piece_map.getPeerCountForPiece(piece_index);
|
|
const target_count: u32 = if (new_count > 0) @intCast(new_count - 1) else 0;
|
|
// CRIT-9 FIX: Properly handle errors from updateAvailability
|
|
self.selector.updateAvailability(piece_index, target_count) catch |err| {
|
|
update_failures += 1;
|
|
// Log error but continue processing other pieces
|
|
// This allows partial cleanup even if some updates fail
|
|
std.log.warn("Failed to update availability for piece {d} during peer removal: {}", .{ piece_index, err });
|
|
};
|
|
}
|
|
// Log summary if there were failures
|
|
if (update_failures > 0) {
|
|
std.log.err("CRIT-9: {d} availability updates failed during peer removal - selector state may be inconsistent", .{update_failures});
|
|
}
|
|
}
|
|
|
|
self.peer_piece_map.removePeer(peer_id_array);
|
|
|
|
// CASCADE PERF: Immediately cancel active downloads from this peer
|
|
// Move them back to pending queue so they can be retried with another peer
|
|
self.cancelActiveDownloadsFromPeerLocked(peer_id_array);
|
|
}
|
|
|
|
/// Cancel all active downloads from a specific peer (INTERNAL - caller must hold lock)
|
|
/// CASCADE PERF: Called when peer disconnects to immediately retry with other peers
|
|
/// Following BitTorrent BEP 6 best practice: peer disconnect = implicit request cancellation
|
|
fn cancelActiveDownloadsFromPeerLocked(self: *DownloadManager, peer_id: [32]u8) void {
|
|
// Collect pieces to cancel (can't modify while iterating)
|
|
// Use 1024 to handle large downloads (1GB = 1024 pieces at 1MB each)
|
|
var to_cancel: [1024]u32 = undefined;
|
|
var cancel_count: usize = 0;
|
|
|
|
var iter = self.active_downloads.iterator();
|
|
while (iter.next()) |entry| {
|
|
if (std.mem.eql(u8, &entry.value_ptr.peer_id, &peer_id)) {
|
|
if (cancel_count < to_cancel.len) {
|
|
to_cancel[cancel_count] = entry.key_ptr.*;
|
|
cancel_count += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Move cancelled downloads back to pending queue
|
|
for (to_cancel[0..cancel_count]) |piece_index| {
|
|
_ = self.active_downloads.remove(piece_index);
|
|
|
|
// SOCKET FIX: Release request tracker slot so new requests can be sent
|
|
self.request_tracker.recordCompletion(peer_id, piece_index);
|
|
|
|
// DISCONNECT FIX: Clear retry tracker for this peer so piece can be
|
|
// immediately retried from another peer without counting against retry limit.
|
|
// Per BitTorrent best practices, peer disconnect should not penalize the piece.
|
|
if (self.retry_trackers.getPtr(piece_index)) |tracker| {
|
|
// Only reset if the last failure was from this peer
|
|
if (tracker.last_peer) |last| {
|
|
if (std.mem.eql(u8, &last, &peer_id)) {
|
|
tracker.reset();
|
|
}
|
|
}
|
|
}
|
|
|
|
// Check if already in pending queue
|
|
var already_pending = false;
|
|
for (self.pending_requests.items) |pending| {
|
|
if (pending.piece_index == piece_index) {
|
|
already_pending = true;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Check if piece is already verified (might have completed from another peer)
|
|
var already_verified = false;
|
|
if (self.selector.availability_map.get(piece_index)) |info| {
|
|
already_verified = info.is_verified;
|
|
}
|
|
|
|
if (!already_pending and !already_verified) {
|
|
// Re-add to pending with priority (front of queue)
|
|
self.pending_requests.insert(self.allocator, 0, DownloadRequest{
|
|
.piece_index = piece_index,
|
|
.peer_id = [_]u8{0} ** 32, // Will be reassigned in processRequests
|
|
.offset = 0,
|
|
.length = @intCast(self.piece_size),
|
|
.priority = .high, // Boost priority for retried pieces
|
|
.requested_at = std.time.timestamp(),
|
|
}) catch {
|
|
std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index});
|
|
};
|
|
}
|
|
}
|
|
|
|
if (cancel_count > 0) {
|
|
std.log.info("CASCADE: Cancelled {} active downloads from disconnected peer, re-queued for immediate retry", .{cancel_count});
|
|
}
|
|
}
|
|
|
|
/// Get peers that have a specific piece
|
|
/// IMP-M1 FIX: Returns list of peer IDs that have this piece
|
|
pub fn getPeersWithPiece(self: *DownloadManager, piece_index: u32, out_buffer: []u8) usize {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
if (self.peer_piece_map.getPeersForPiece(piece_index)) |peers| {
|
|
var written: usize = 0;
|
|
var iter = peers.iterator();
|
|
while (iter.next()) |entry| {
|
|
if (written + 32 > out_buffer.len) break;
|
|
@memcpy(out_buffer[written..][0..32], &entry.key_ptr.*);
|
|
written += 32;
|
|
}
|
|
return written / 32; // Return number of peers
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
// ========== ENDGAME MODE ==========
|
|
// When download is nearly complete (>95%), request remaining pieces from ALL
|
|
// available peers simultaneously. This prevents a single slow peer from
|
|
// bottlenecking the final pieces.
|
|
|
|
/// Check if we should enter endgame mode based on progress
|
|
/// Call this periodically or after piece completions
|
|
pub fn checkEndgameMode(self: *DownloadManager) void {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
self.checkEndgameModeLocked();
|
|
}
|
|
|
|
fn checkEndgameModeLocked(self: *DownloadManager) void {
|
|
if (self.endgame_active) return; // Already in endgame
|
|
|
|
const progress = self.state.getCompletionPercent() / 100.0;
|
|
if (progress >= self.endgame_threshold) {
|
|
self.endgame_active = true;
|
|
self.endgame_broadcast_pending = true; // PHASE 5: Trigger broadcast
|
|
const remaining = self.state.piece_count - self.state.completed_pieces.load(.acquire);
|
|
std.log.info("ENDGAME: Activated at {d:.1}% ({d} pieces left) - broadcasting duplicate requests", .{ progress * 100, remaining });
|
|
}
|
|
}
|
|
|
|
/// PHASE 5: Check and clear broadcast pending flag (call from outside lock)
|
|
pub fn needsEndgameBroadcast(self: *DownloadManager) bool {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
if (self.endgame_broadcast_pending) {
|
|
self.endgame_broadcast_pending = false;
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// Check if endgame mode is active
|
|
pub fn isInEndgame(self: *DownloadManager) bool {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
return self.endgame_active;
|
|
}
|
|
|
|
/// In endgame mode, check if we've already requested this piece from this peer
|
|
fn hasEndgameRequestLocked(self: *DownloadManager, piece_index: u32, peer_id: [32]u8) bool {
|
|
if (self.endgame_requests.get(piece_index)) |peer_list| {
|
|
for (peer_list.items) |existing_peer| {
|
|
if (std.mem.eql(u8, &existing_peer, &peer_id)) {
|
|
return true;
|
|
}
|
|
}
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// Record an endgame request for tracking
|
|
fn addEndgameRequestLocked(self: *DownloadManager, piece_index: u32, peer_id: [32]u8) void {
|
|
const result = self.endgame_requests.getOrPut(piece_index) catch return;
|
|
if (!result.found_existing) {
|
|
result.value_ptr.* = std.ArrayList([32]u8){};
|
|
}
|
|
result.value_ptr.append(self.allocator, peer_id) catch return;
|
|
}
|
|
|
|
/// ENDGAME FIX: Remove a specific peer from endgame tracking for a piece
|
|
/// Called when a request fails so the piece can be re-requested from that peer
|
|
fn removeEndgameRequestLocked(self: *DownloadManager, piece_index: u32, peer_id: [32]u8) void {
|
|
if (self.endgame_requests.getPtr(piece_index)) |peer_list| {
|
|
var i: usize = 0;
|
|
while (i < peer_list.items.len) {
|
|
if (std.mem.eql(u8, &peer_list.items[i], &peer_id)) {
|
|
_ = peer_list.orderedRemove(i);
|
|
// Don't increment i since we removed an element
|
|
} else {
|
|
i += 1;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/// Cancel all pending endgame requests for a completed piece
|
|
fn cancelEndgameRequestsLocked(self: *DownloadManager, piece_index: u32) void {
|
|
// Remove from endgame tracking
|
|
if (self.endgame_requests.fetchRemove(piece_index)) |kv| {
|
|
var list = kv.value;
|
|
list.deinit(self.allocator);
|
|
}
|
|
|
|
// Also remove any duplicate pending requests for this piece
|
|
var i: usize = 0;
|
|
var removed: usize = 0;
|
|
while (i < self.pending_requests.items.len) {
|
|
if (self.pending_requests.items[i].piece_index == piece_index) {
|
|
_ = self.pending_requests.orderedRemove(i);
|
|
removed += 1;
|
|
} else {
|
|
i += 1;
|
|
}
|
|
}
|
|
if (removed > 0) {
|
|
std.log.debug("ENDGAME: Cancelled {d} duplicate pending requests for piece {d}", .{ removed, piece_index });
|
|
}
|
|
}
|
|
|
|
/// Get count of remaining pieces (for endgame decisions)
|
|
pub fn getRemainingPieceCount(self: *DownloadManager) u32 {
|
|
return self.state.piece_count - self.state.completed_pieces.load(.acquire);
|
|
}
|
|
|
|
/// Get list of incomplete piece indices for endgame requests
|
|
/// Caller must free returned slice
|
|
pub fn getIncompletePieces(self: *DownloadManager) Error![]u32 {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
var incomplete = std.ArrayList(u32){};
|
|
errdefer incomplete.deinit(self.allocator);
|
|
|
|
var iter = self.selector.availability_map.iterator();
|
|
while (iter.next()) |entry| {
|
|
const piece_info = entry.value_ptr.*;
|
|
if (!piece_info.is_downloaded and !piece_info.is_verified) {
|
|
incomplete.append(self.allocator, piece_info.piece_index) catch return Error.OutOfMemory;
|
|
}
|
|
}
|
|
|
|
return incomplete.toOwnedSlice(self.allocator) catch return Error.OutOfMemory;
|
|
}
|
|
|
|
/// PHASE 5: Get all peers that have a specific piece and haven't been requested yet (for endgame broadcast)
|
|
pub fn getUnrequestedPeersWithPiece(self: *DownloadManager, piece_index: u32) Error![]const [32]u8 {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
var peers = std.ArrayList([32]u8){};
|
|
errdefer peers.deinit(self.allocator);
|
|
|
|
var iter = self.peer_piece_map.peer_pieces.iterator();
|
|
while (iter.next()) |entry| {
|
|
const peer_id = entry.key_ptr.*;
|
|
const bitset = entry.value_ptr.*;
|
|
if (bitset.contains(piece_index)) {
|
|
// Skip if already requested from this peer in endgame
|
|
if (!self.hasEndgameRequestLocked(piece_index, peer_id)) {
|
|
peers.append(self.allocator, peer_id) catch return Error.OutOfMemory;
|
|
}
|
|
}
|
|
}
|
|
|
|
return peers.toOwnedSlice(self.allocator) catch return Error.OutOfMemory;
|
|
}
|
|
|
|
/// PHASE 5: Queue endgame requests for a piece to all available peers
|
|
/// Returns number of requests queued
|
|
pub fn queueEndgameRequests(
|
|
self: *DownloadManager,
|
|
piece_index: u32,
|
|
priority: PieceAvailability.Priority,
|
|
) Error!u32 {
|
|
if (!self.endgame_active) return 0;
|
|
|
|
const peers = try self.getUnrequestedPeersWithPiece(piece_index);
|
|
defer self.allocator.free(peers);
|
|
|
|
var queued: u32 = 0;
|
|
for (peers) |peer_id| {
|
|
self.requestPiece(piece_index, priority, &peer_id) catch |err| {
|
|
std.log.debug("ENDGAME: Failed to queue piece {} to peer: {}", .{ piece_index, err });
|
|
continue;
|
|
};
|
|
queued += 1;
|
|
}
|
|
|
|
if (queued > 0) {
|
|
std.log.debug("ENDGAME: Queued piece {} to {} peers", .{ piece_index, queued });
|
|
}
|
|
|
|
return queued;
|
|
}
|
|
|
|
/// PHASE 5: Broadcast all remaining pieces to all available peers
|
|
/// Call this when endgame mode activates
|
|
pub fn broadcastEndgameRequests(self: *DownloadManager) Error!u32 {
|
|
if (!self.endgame_active) return 0;
|
|
|
|
const incomplete = try self.getIncompletePieces();
|
|
defer self.allocator.free(incomplete);
|
|
|
|
var total_queued: u32 = 0;
|
|
for (incomplete) |piece_index| {
|
|
const queued = try self.queueEndgameRequests(piece_index, .high);
|
|
total_queued += queued;
|
|
}
|
|
|
|
if (total_queued > 0) {
|
|
std.log.info("ENDGAME: Broadcast {} duplicate requests for {} remaining pieces", .{ total_queued, incomplete.len });
|
|
}
|
|
|
|
return total_queued;
|
|
}
|
|
|
|
/// Request piece download
|
|
/// In endgame mode, allows requesting same piece from multiple peers
|
|
/// Maximum pending queue size to prevent memory exhaustion
|
|
/// With 1024 pieces and 64 max peers, theoretical max needed is 65536
|
|
/// Adding some buffer for retries and endgame mode
|
|
const MAX_PENDING_QUEUE_SIZE: usize = 32768;
|
|
|
|
pub fn requestPiece(
|
|
self: *DownloadManager,
|
|
piece_index: u32,
|
|
priority: PieceAvailability.Priority,
|
|
peer_id: []const u8,
|
|
) Error!void {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// QUEUE LIMIT: Prevent runaway queue growth
|
|
// If queue is too large, reject new requests - they can retry later
|
|
if (self.pending_requests.items.len >= MAX_PENDING_QUEUE_SIZE) {
|
|
return Error.QueueFull;
|
|
}
|
|
|
|
// Convert peer_id to fixed array for endgame tracking
|
|
var peer_id_array: [32]u8 = [_]u8{0} ** 32;
|
|
const copy_len = @min(peer_id.len, 32);
|
|
@memcpy(peer_id_array[0..copy_len], peer_id[0..copy_len]);
|
|
|
|
// Check endgame mode periodically
|
|
self.checkEndgameModeLocked();
|
|
|
|
const piece_info = self.selector.availability_map.get(piece_index) orelse return Error.InvalidData;
|
|
if (piece_info.is_downloaded or piece_info.is_verified) {
|
|
return; // Already have this piece
|
|
}
|
|
|
|
// ENDGAME MODE: Allow duplicate requests from different peers
|
|
if (self.endgame_active) {
|
|
// In endgame, check if we've already requested from THIS peer
|
|
if (self.hasEndgameRequestLocked(piece_index, peer_id_array)) {
|
|
return; // Already requested from this peer
|
|
}
|
|
// Track this endgame request
|
|
self.addEndgameRequestLocked(piece_index, peer_id_array);
|
|
} else {
|
|
// Normal mode: only one request per piece
|
|
if (self.active_downloads.contains(piece_index)) {
|
|
return; // Already downloading
|
|
}
|
|
|
|
// Check if piece is already in pending queue (prevent duplicates)
|
|
for (self.pending_requests.items) |pending| {
|
|
if (pending.piece_index == piece_index) {
|
|
std.log.debug("Piece {} already in pending queue, skipping add", .{piece_index});
|
|
return;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Check retry state - don't request if we've exhausted retries or need to wait
|
|
if (!self.canRequestPieceLocked(piece_index)) {
|
|
return; // Either max retries exceeded or backoff period not elapsed
|
|
}
|
|
|
|
// Create download request
|
|
// Note: piece size comes from manager config, not from availability
|
|
|
|
// OVERFLOW FIX: Use checked multiplication for offset calculation
|
|
const piece_offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
|
|
|
|
// MEM-M2 FIX: Check piece_size fits in u32 before casting
|
|
// This prevents undefined behavior from overflow on very large piece sizes
|
|
if (self.piece_size > std.math.maxInt(u32)) {
|
|
return Error.BufferOverflow;
|
|
}
|
|
const piece_size_u32: u32 = @intCast(self.piece_size);
|
|
|
|
const request = DownloadRequest.create(
|
|
piece_index,
|
|
piece_offset,
|
|
piece_size_u32,
|
|
priority,
|
|
peer_id,
|
|
) orelse {
|
|
// MEM-M3: Invalid request parameters
|
|
return Error.InvalidData;
|
|
};
|
|
|
|
try self.pending_requests.append(self.allocator, request);
|
|
std.log.debug("Added piece {} to pending requests (queue size={})", .{ piece_index, self.pending_requests.items.len });
|
|
}
|
|
|
|
/// Process pending requests and start downloads
|
|
/// PERF FIX: Use bulk removal instead of O(n) orderedRemove per item
|
|
pub fn processRequests(self: *DownloadManager, max_concurrent: usize) Error!void {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// Clean up expired requests
|
|
self.cleanupExpiredRequestsLocked();
|
|
|
|
// Clean up stuck active downloads that never received data
|
|
self.cleanupStuckActiveDownloadsLocked(max_concurrent);
|
|
|
|
// STALL FIX: Periodically clean up completed pieces from entire pending queue
|
|
// This prevents queue bloat when pieces complete out of order
|
|
self.cleanupCompletedPiecesFromPendingLocked();
|
|
|
|
// Start new downloads if we have capacity
|
|
var active_count = self.active_downloads.count();
|
|
|
|
// PERF FIX: The old code did orderedRemove(0) per item which is O(n) each.
|
|
// With max_concurrent=128 and 81920 pending items, that's 10M operations!
|
|
// New approach: count how many to remove, then shift in bulk.
|
|
|
|
var to_remove: usize = 0;
|
|
const items = self.pending_requests.items;
|
|
|
|
// STUCK FIX v2: Collect pieces with no available peer to re-add at back of queue
|
|
var peerless_pieces: std.ArrayList(DownloadRequest) = .{};
|
|
defer peerless_pieces.deinit(self.allocator);
|
|
|
|
// First pass: process items and count how many to remove from front
|
|
while (to_remove < items.len and active_count < max_concurrent) {
|
|
const request = items[to_remove];
|
|
|
|
// Check if piece is still needed
|
|
const piece_info = self.selector.availability_map.get(request.piece_index) orelse {
|
|
to_remove += 1;
|
|
continue;
|
|
};
|
|
|
|
if (piece_info.is_downloaded or piece_info.is_verified) {
|
|
to_remove += 1;
|
|
continue;
|
|
}
|
|
|
|
// RETRY FIX: Try to find a valid peer for this piece
|
|
// The request's peer_id might be from an offline peer (e.g., after seeder goes offline)
|
|
var selected_peer_id = request.peer_id;
|
|
var found_peer = false;
|
|
|
|
// Get the last failed peer from retry_trackers to avoid it
|
|
var failed_peer_id: ?[32]u8 = null;
|
|
if (self.retry_trackers.get(request.piece_index)) |tracker| {
|
|
failed_peer_id = tracker.last_peer;
|
|
}
|
|
|
|
// Check if any peer has this piece and try to find an alternative
|
|
if (self.peer_piece_map.getPeersForPiece(request.piece_index)) |peers| {
|
|
// First pass: find a peer that isn't the failed one
|
|
var iter = peers.iterator();
|
|
while (iter.next()) |entry| {
|
|
const peer_id = entry.key_ptr.*;
|
|
// Skip the peer that just failed
|
|
if (failed_peer_id) |failed| {
|
|
if (std.mem.eql(u8, &peer_id, &failed)) {
|
|
continue;
|
|
}
|
|
}
|
|
// Also skip the peer in the request (which may have failed earlier)
|
|
if (!std.mem.eql(u8, &peer_id, &request.peer_id)) {
|
|
selected_peer_id = peer_id;
|
|
found_peer = true;
|
|
break;
|
|
}
|
|
}
|
|
// If only the failed peer is available, use it anyway (better than nothing)
|
|
if (!found_peer and peers.count() > 0) {
|
|
var first_iter = peers.iterator();
|
|
if (first_iter.next()) |first_entry| {
|
|
selected_peer_id = first_entry.key_ptr.*;
|
|
found_peer = true;
|
|
}
|
|
}
|
|
}
|
|
|
|
// STUCK FIX v2: If peer_id is zero (from stuck download retry) and no peer found,
|
|
// move piece to BACK of queue so it doesn't block other pieces that might have peers.
|
|
// The original STUCK FIX used 'break' which stopped ALL processing when one piece had no peer.
|
|
const zero_peer: [32]u8 = [_]u8{0} ** 32;
|
|
if (!found_peer and std.mem.eql(u8, &selected_peer_id, &zero_peer)) {
|
|
// Log when we hit this case
|
|
if (self.pending_requests.items.len < 100 or request.piece_index % 100 == 0) {
|
|
std.log.debug("STUCK FIX v2: Piece {} has no peer, moving to back of queue ({} pending)", .{
|
|
request.piece_index,
|
|
self.pending_requests.items.len,
|
|
});
|
|
}
|
|
// Mark for removal from front, will be re-added at back
|
|
to_remove += 1;
|
|
// Collect for re-adding at back (handled after bulk removal)
|
|
peerless_pieces.append(self.allocator, request) catch {
|
|
// If append fails, the piece is lost - better to break than lose pieces
|
|
to_remove -= 1;
|
|
break;
|
|
};
|
|
continue;
|
|
}
|
|
|
|
// Start download with selected peer (or original if no alternative found)
|
|
const active_download = ActiveDownload{
|
|
.piece_index = request.piece_index,
|
|
.peer_id = selected_peer_id,
|
|
.offset = request.offset,
|
|
.length = request.length,
|
|
.downloaded_bytes = 0,
|
|
.started_at = std.time.timestamp(),
|
|
.status = .downloading,
|
|
};
|
|
|
|
self.active_downloads.put(request.piece_index, active_download) catch |err| {
|
|
std.log.warn("Failed to add active download: {}", .{err});
|
|
break;
|
|
};
|
|
|
|
to_remove += 1;
|
|
active_count += 1;
|
|
}
|
|
|
|
// Bulk remove: shift remaining items down in one operation
|
|
if (to_remove > 0) {
|
|
const remaining = items.len - to_remove;
|
|
if (remaining > 0) {
|
|
std.mem.copyForwards(
|
|
DownloadRequest,
|
|
self.pending_requests.items[0..remaining],
|
|
self.pending_requests.items[to_remove..],
|
|
);
|
|
}
|
|
self.pending_requests.items.len = remaining;
|
|
}
|
|
|
|
// STUCK FIX v2: Re-add peerless pieces at the BACK of the queue
|
|
// This allows other pieces with available peers to be processed first
|
|
for (peerless_pieces.items) |request| {
|
|
self.pending_requests.append(self.allocator, request) catch {
|
|
std.log.warn("Failed to re-queue peerless piece {} at back", .{request.piece_index});
|
|
};
|
|
}
|
|
}
|
|
|
|
/// Handle piece data received
|
|
pub fn handlePieceData(
|
|
self: *DownloadManager,
|
|
piece_index: u32,
|
|
data: []const u8,
|
|
expected_hash: PieceHash,
|
|
) Error!void {
|
|
// Verify piece integrity
|
|
const is_valid = try HashUtils.verify(data, expected_hash);
|
|
if (!is_valid) {
|
|
// Hash verification failed - trigger retry logic
|
|
try self.handleDownloadFailure(piece_index, "Hash verification failed");
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// Write piece to file if writer is available
|
|
if (self.file_writer) |*writer| {
|
|
try writer.writePiece(piece_index, data, data.len);
|
|
try writer.flush();
|
|
}
|
|
|
|
// Update state
|
|
self.state.addDownloadedBytes(data.len);
|
|
self.state.addVerifiedBytes(data.len);
|
|
self.state.markPieceCompleted();
|
|
|
|
// Update selector
|
|
try self.selector.markDownloaded(piece_index);
|
|
try self.selector.markVerified(piece_index);
|
|
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// Clear retry tracker on success
|
|
if (self.retry_trackers.getPtr(piece_index)) |tracker| {
|
|
tracker.reset();
|
|
_ = self.retry_trackers.remove(piece_index);
|
|
}
|
|
|
|
// PERF: Get peer_id and release pipeline slot before removing from active downloads
|
|
if (self.active_downloads.get(piece_index)) |active| {
|
|
self.request_tracker.recordCompletion(active.peer_id, piece_index);
|
|
}
|
|
|
|
// Remove from active downloads
|
|
_ = self.active_downloads.remove(piece_index);
|
|
|
|
// Check if we should enter endgame mode after this completion
|
|
self.checkEndgameModeLocked();
|
|
|
|
// ENDGAME: Cancel duplicate requests for this piece
|
|
if (self.endgame_active) {
|
|
self.cancelEndgameRequestsLocked(piece_index);
|
|
}
|
|
}
|
|
|
|
/// Handle download failure with retry logic
|
|
/// IMP-M3 FIX: Now logs and tracks the failure reason
|
|
/// RETRY FIX: Now properly re-queues pieces for retry
|
|
pub fn handleDownloadFailure(self: *DownloadManager, piece_index: u32, reason: []const u8) Error!void {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// Get the failed peer ID before removing from active downloads
|
|
var failed_peer_id: [32]u8 = [_]u8{0} ** 32;
|
|
if (self.active_downloads.getPtr(piece_index)) |download| {
|
|
download.status = .failed;
|
|
failed_peer_id = download.peer_id;
|
|
}
|
|
|
|
// PERF: Release pipeline slot on failure so we can send more requests
|
|
self.request_tracker.recordCompletion(failed_peer_id, piece_index);
|
|
|
|
// ENDGAME FIX: Clear endgame tracking for failed peer so retries can happen
|
|
// Without this, hasEndgameRequestLocked blocks re-requests to the same peer
|
|
if (self.endgame_active) {
|
|
self.removeEndgameRequestLocked(piece_index, failed_peer_id);
|
|
}
|
|
|
|
// IMP-M3 FIX: Log the failure with the actual reason
|
|
std.log.info("Download failure for piece {d}: {s}", .{ piece_index, reason });
|
|
|
|
// Get or create retry tracker for this piece
|
|
const gop = try self.retry_trackers.getOrPut(piece_index);
|
|
if (!gop.found_existing) {
|
|
gop.value_ptr.* = PieceRetryTracker.init();
|
|
}
|
|
|
|
const tracker = gop.value_ptr;
|
|
tracker.recordFailure(&failed_peer_id);
|
|
|
|
// CRIT-8 FIX: Copy failure reason to owned storage (not just pointer)
|
|
tracker.setLastFailureReason(reason);
|
|
|
|
// Remove from active downloads first
|
|
_ = self.active_downloads.remove(piece_index);
|
|
|
|
if (tracker.shouldRetry()) {
|
|
// RETRY FIX: Actually re-add the piece to pending queue for retry
|
|
// Try to find an alternative peer that has this piece
|
|
var retry_peer_id: [32]u8 = failed_peer_id; // Default to same peer if no alternative
|
|
if (self.peer_piece_map.getPeersForPiece(piece_index)) |peers| {
|
|
var iter = peers.iterator();
|
|
while (iter.next()) |entry| {
|
|
// Skip the peer that just failed
|
|
if (!std.mem.eql(u8, &entry.key_ptr.*, &failed_peer_id)) {
|
|
retry_peer_id = entry.key_ptr.*;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
|
|
// OVERFLOW FIX: Use checked multiplication for offset calculation
|
|
const piece_offset = std.math.mul(u64, piece_index, self.piece_size) catch {
|
|
std.log.err("Piece offset overflow for piece {d}", .{piece_index});
|
|
self.state.markPieceFailed();
|
|
return;
|
|
};
|
|
|
|
// MEM-M2 FIX: Check piece_size fits in u32
|
|
if (self.piece_size > std.math.maxInt(u32)) {
|
|
std.log.err("Piece size too large for retry", .{});
|
|
self.state.markPieceFailed();
|
|
return;
|
|
}
|
|
|
|
// Create retry request
|
|
const request = DownloadRequest.create(
|
|
piece_index,
|
|
piece_offset,
|
|
@intCast(self.piece_size),
|
|
PieceAvailability.Priority.high, // Retry with high priority
|
|
&retry_peer_id,
|
|
) orelse {
|
|
std.log.err("Failed to create retry request for piece {d}", .{piece_index});
|
|
self.state.markPieceFailed();
|
|
return;
|
|
};
|
|
|
|
// Check if piece is already in pending queue (prevent duplicates)
|
|
var already_pending = false;
|
|
for (self.pending_requests.items) |pending| {
|
|
if (pending.piece_index == piece_index) {
|
|
already_pending = true;
|
|
break;
|
|
}
|
|
}
|
|
if (already_pending) {
|
|
std.log.debug("Piece {} already in pending queue, skipping retry re-add", .{piece_index});
|
|
return;
|
|
}
|
|
|
|
// Add back to pending queue
|
|
self.pending_requests.append(self.allocator, request) catch |err| {
|
|
std.log.err("Failed to re-queue piece {d} for retry: {}", .{ piece_index, err });
|
|
self.state.markPieceFailed();
|
|
return;
|
|
};
|
|
|
|
std.log.info("Piece {d} re-queued for retry (attempt {d}/{d})", .{
|
|
piece_index,
|
|
tracker.retry_count,
|
|
PieceRetryTracker.MAX_RETRIES,
|
|
});
|
|
} else {
|
|
// Max retries exceeded - mark as permanently failed
|
|
self.state.markPieceFailed();
|
|
|
|
// Log permanent failure with reason
|
|
std.log.warn("Piece {d} failed permanently after {d} retries. Last reason: {s}", .{
|
|
piece_index,
|
|
tracker.retry_count,
|
|
tracker.getLastFailureReason(),
|
|
});
|
|
}
|
|
}
|
|
|
|
/// Check if a piece can be requested based on retry state
|
|
pub fn canRequestPiece(self: *DownloadManager, piece_index: u32) bool {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
return self.canRequestPieceLocked(piece_index);
|
|
}
|
|
|
|
/// Check if a piece can be requested (INTERNAL - caller must hold lock)
|
|
fn canRequestPieceLocked(self: *DownloadManager, piece_index: u32) bool {
|
|
// Check if we have a retry tracker for this piece
|
|
if (self.retry_trackers.get(piece_index)) |tracker| {
|
|
// If we've exhausted retries, don't allow request
|
|
if (!tracker.shouldRetry()) {
|
|
return false;
|
|
}
|
|
// Check if enough time has passed for retry
|
|
return tracker.canRetryNow();
|
|
}
|
|
// No retry tracker means this is first attempt
|
|
return true;
|
|
}
|
|
|
|
/// Select peer for piece download, avoiding failed peers
|
|
/// IMP-M1 FIX: Now verifies peer actually has the piece before selecting
|
|
pub fn selectPeerForPiece(self: *DownloadManager, piece_index: u32, available_peers: []const []const u8) ?[]const u8 {
|
|
if (available_peers.len == 0) return null;
|
|
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// IMP-M1 FIX: Get the failed peer ID if any
|
|
var failed_peer_id: ?[32]u8 = null;
|
|
if (self.retry_trackers.get(piece_index)) |tracker| {
|
|
failed_peer_id = tracker.last_peer;
|
|
}
|
|
|
|
// IMP-M1 FIX: First try to find a peer that:
|
|
// 1. Actually has this piece (according to our tracking)
|
|
// 2. Is not the peer that failed last time
|
|
for (available_peers) |peer| {
|
|
var peer_id_array: [32]u8 = [_]u8{0} ** 32;
|
|
const copy_len = @min(peer.len, 32);
|
|
@memcpy(peer_id_array[0..copy_len], peer[0..copy_len]);
|
|
|
|
// Check if this peer actually has the piece
|
|
if (!self.peer_piece_map.peerHasPiece(peer_id_array, piece_index)) {
|
|
continue; // Skip peers that don't have the piece
|
|
}
|
|
|
|
// Check if this is not the failed peer
|
|
if (failed_peer_id) |failed_id| {
|
|
if (mem.eql(u8, &peer_id_array, &failed_id)) {
|
|
continue; // Skip the failed peer for now
|
|
}
|
|
}
|
|
|
|
return peer; // Found a good peer
|
|
}
|
|
|
|
// IMP-M1 FIX: If no alternative peer found, try the failed peer if it has the piece
|
|
// (better than nothing after backoff delay)
|
|
for (available_peers) |peer| {
|
|
var peer_id_array: [32]u8 = [_]u8{0} ** 32;
|
|
const copy_len = @min(peer.len, 32);
|
|
@memcpy(peer_id_array[0..copy_len], peer[0..copy_len]);
|
|
|
|
if (self.peer_piece_map.peerHasPiece(peer_id_array, piece_index)) {
|
|
return peer;
|
|
}
|
|
}
|
|
|
|
// NO FALLBACK FIX: Don't send requests to peers who aren't known to have the piece.
|
|
// Falling back to a random peer causes requests to go to peers without the piece,
|
|
// resulting in timeouts (the receiver ignores the request since they don't have it).
|
|
// Instead, return null and let the caller wait for a "have" broadcast from a peer
|
|
// who actually has the piece. This prevents stuck downloads and wasted network traffic.
|
|
return null;
|
|
}
|
|
|
|
/// Clean up expired requests (INTERNAL - caller must hold lock)
|
|
/// NOTE: Disabled for large files - pending requests should wait in queue, not expire.
|
|
/// Active downloads that stall are handled by cleanupStuckActiveDownloadsLocked.
|
|
fn cleanupExpiredRequestsLocked(self: *DownloadManager) void {
|
|
// Don't expire pending requests - they should wait until processed.
|
|
// With large files (8000+ pieces), the queue takes a long time to drain
|
|
// and expiring requests would cause mass loss of work.
|
|
_ = self;
|
|
}
|
|
|
|
/// Clean up stuck active downloads that haven't received data (INTERNAL - caller must hold lock)
|
|
/// FIX: Active downloads could get stuck if piece_data response failed to send.
|
|
/// This function detects and removes such stuck downloads so they can be retried.
|
|
/// CONCURRENCY FIX: Batch size now matches max_concurrent to handle all stuck downloads in one pass.
|
|
fn cleanupStuckActiveDownloadsLocked(self: *DownloadManager, max_concurrent: usize) void {
|
|
const now = std.time.timestamp();
|
|
// THROUGHPUT FIX: 10 seconds provides a balance between fast retry and avoiding
|
|
// premature retries. 5 seconds was too aggressive and caused excessive retries.
|
|
// 15 seconds was too slow for localhost. For WAN, consider 15 seconds.
|
|
const active_timeout: i64 = 10;
|
|
|
|
// Collect piece indices and peer_ids to remove (can't modify while iterating)
|
|
// CONCURRENCY FIX: Use max_concurrent as batch size instead of hardcoded 64
|
|
// This ensures all stuck downloads can be cleaned up in a single pass
|
|
const StuckInfo = struct {
|
|
piece_index: u32,
|
|
peer_id: [32]u8,
|
|
};
|
|
const batch_size = @max(64, max_concurrent); // At least 64, or max_concurrent if higher
|
|
const to_remove = self.allocator.alloc(StuckInfo, batch_size) catch {
|
|
std.log.warn("Failed to allocate stuck download cleanup buffer", .{});
|
|
return;
|
|
};
|
|
defer self.allocator.free(to_remove);
|
|
var remove_count: usize = 0;
|
|
|
|
var iter = self.active_downloads.iterator();
|
|
while (iter.next()) |entry| {
|
|
const active = entry.value_ptr;
|
|
const elapsed = now - active.started_at;
|
|
|
|
// If download has been active too long without receiving data, consider it stuck
|
|
// Sentinel value 1 means request was sent but no data received yet
|
|
if (elapsed > active_timeout and active.downloaded_bytes <= 1) {
|
|
if (remove_count < to_remove.len) {
|
|
to_remove[remove_count] = .{
|
|
.piece_index = entry.key_ptr.*,
|
|
.peer_id = active.peer_id,
|
|
};
|
|
remove_count += 1;
|
|
std.log.warn("Active download for piece {} stuck ({} seconds without data), will retry", .{
|
|
entry.key_ptr.*,
|
|
elapsed,
|
|
});
|
|
}
|
|
}
|
|
}
|
|
|
|
// Remove stuck downloads and re-add to pending for retry
|
|
// NOTE: Can't call handleDownloadFailure here as it would deadlock (we already hold the lock)
|
|
for (to_remove[0..remove_count]) |info| {
|
|
_ = self.active_downloads.remove(info.piece_index);
|
|
|
|
// STUCK FIX: Release the request tracker slot so new requests can be sent!
|
|
// Without this, the tracker thinks the request is still in-flight and blocks new requests.
|
|
self.request_tracker.recordCompletion(info.peer_id, info.piece_index);
|
|
|
|
// ENDGAME FIX: Clear endgame tracking for stuck peer so retries can happen
|
|
if (self.endgame_active) {
|
|
self.removeEndgameRequestLocked(info.piece_index, info.peer_id);
|
|
}
|
|
|
|
// RETRY FIX: Update retry_trackers so selectPeerForPiece avoids this failed peer
|
|
// This ensures the retry goes to a different peer, not the one that just timed out.
|
|
const gop = self.retry_trackers.getOrPut(info.piece_index) catch continue;
|
|
if (!gop.found_existing) {
|
|
gop.value_ptr.* = PieceRetryTracker.init();
|
|
}
|
|
gop.value_ptr.recordFailure(&info.peer_id);
|
|
|
|
// DUPLICATE FIX: Check if piece is already in pending queue
|
|
var already_pending = false;
|
|
for (self.pending_requests.items) |pending| {
|
|
if (pending.piece_index == info.piece_index) {
|
|
already_pending = true;
|
|
break;
|
|
}
|
|
}
|
|
if (already_pending) {
|
|
std.log.debug("Piece {} already in pending queue, skipping re-add", .{info.piece_index});
|
|
continue;
|
|
}
|
|
|
|
// Create retry request
|
|
const piece_offset = std.math.mul(u64, info.piece_index, self.piece_size) catch continue;
|
|
const piece_size_u32: u32 = if (self.piece_size > std.math.maxInt(u32))
|
|
std.math.maxInt(u32)
|
|
else
|
|
@intCast(self.piece_size);
|
|
|
|
const request = DownloadRequest{
|
|
.piece_index = info.piece_index,
|
|
.offset = piece_offset,
|
|
.length = piece_size_u32,
|
|
.priority = .normal,
|
|
.requested_at = std.time.timestamp(),
|
|
// SOCKET FIX: Zero out peer_id so request can be assigned to a different peer.
|
|
// Using the same failed peer_id would cause the retry to fail again.
|
|
// This matches the behavior in cancelActiveDownloadsFromPeerLocked.
|
|
.peer_id = [_]u8{0} ** 32,
|
|
};
|
|
|
|
// Re-add to FRONT of pending queue for retry (not back!)
|
|
// This ensures retry pieces don't get buried behind new requests
|
|
self.pending_requests.insert(self.allocator, 0, request) catch {
|
|
std.log.warn("Failed to re-queue piece {} for retry", .{info.piece_index});
|
|
};
|
|
}
|
|
|
|
// ADAPTIVE: Track stuck download count for concurrency controller
|
|
if (remove_count > 0) {
|
|
_ = self.stuck_downloads_cleaned.fetchAdd(@intCast(remove_count), .release);
|
|
}
|
|
}
|
|
|
|
/// ADAPTIVE: Get and reset stuck downloads counter
|
|
/// Used by adaptive concurrency controller to detect timeouts
|
|
pub fn getAndResetStuckDownloads(self: *DownloadManager) u32 {
|
|
return self.stuck_downloads_cleaned.swap(0, .acq_rel);
|
|
}
|
|
|
|
/// STALL FIX: Clean up completed pieces from entire pending queue
|
|
/// This prevents queue bloat when pieces complete out of order.
|
|
/// Without this, completed pieces stay in the queue until they reach the front.
|
|
fn cleanupCompletedPiecesFromPendingLocked(self: *DownloadManager) void {
|
|
// Only run cleanup periodically to avoid performance hit
|
|
const should_cleanup = self.pending_requests.items.len > 1000;
|
|
if (!should_cleanup) return;
|
|
|
|
// PERF FIX: Use in-place filter instead of O(n) orderedRemove per item.
|
|
// Old approach was O(n²), new is O(n).
|
|
var write_idx: usize = 0;
|
|
const items = self.pending_requests.items;
|
|
|
|
for (items) |request| {
|
|
const piece_info = self.selector.availability_map.get(request.piece_index) orelse continue;
|
|
if (piece_info.is_downloaded or piece_info.is_verified) continue;
|
|
|
|
// Keep this item
|
|
items[write_idx] = request;
|
|
write_idx += 1;
|
|
}
|
|
|
|
const removed = items.len - write_idx;
|
|
self.pending_requests.items.len = write_idx;
|
|
|
|
if (removed > 0) {
|
|
std.log.info("STALL FIX: Cleaned up {} completed pieces from pending queue (now {} items)", .{ removed, self.pending_requests.items.len });
|
|
}
|
|
}
|
|
|
|
/// Get download statistics
|
|
pub fn getStats(self: *DownloadManager) DownloadStats {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
var retrying_pieces: u32 = 0;
|
|
var permanently_failed: u32 = 0;
|
|
|
|
var iter = self.retry_trackers.iterator();
|
|
while (iter.next()) |entry| {
|
|
const tracker = entry.value_ptr;
|
|
if (tracker.shouldRetry()) {
|
|
retrying_pieces += 1;
|
|
} else {
|
|
permanently_failed += 1;
|
|
}
|
|
}
|
|
|
|
return DownloadStats{
|
|
.state = self.state,
|
|
.pending_requests = self.pending_requests.items.len,
|
|
.active_downloads = self.active_downloads.count(),
|
|
.progress = self.state.getProgress(),
|
|
.speed = self.state.getDownloadSpeed(),
|
|
.time_remaining = self.state.getTimeRemaining(),
|
|
.retrying_pieces = retrying_pieces,
|
|
.permanently_failed = permanently_failed,
|
|
};
|
|
}
|
|
|
|
/// Get retry information for a specific piece
|
|
pub fn getPieceRetryInfo(self: *DownloadManager, piece_index: u32) ?PieceRetryInfo {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
if (self.retry_trackers.get(piece_index)) |tracker| {
|
|
return PieceRetryInfo{
|
|
.retry_count = tracker.retry_count,
|
|
.can_retry = tracker.shouldRetry(),
|
|
.next_retry_ms = if (tracker.shouldRetry()) tracker.getRetryDelay() else 0,
|
|
.last_attempt_ms = tracker.last_attempt,
|
|
};
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// Check if download is complete
|
|
pub fn isComplete(self: *const DownloadManager) bool {
|
|
return self.state.isComplete();
|
|
}
|
|
|
|
/// Get pieces that still need to be downloaded
|
|
pub fn getNeededPieces(self: *DownloadManager, max_pieces: usize) Error![]u32 {
|
|
return self.selector.selectNext(max_pieces);
|
|
}
|
|
|
|
/// Set piece priority
|
|
pub fn setPiecePriority(self: *DownloadManager, piece_index: u32, priority: PieceAvailability.Priority) Error!void {
|
|
try self.selector.setPriority(piece_index, priority);
|
|
}
|
|
|
|
/// PERF: Count pending requests for a specific peer
|
|
pub fn getPendingCountForPeer(self: *DownloadManager, peer_id: [32]u8) usize {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
return self.getPendingCountForPeerLocked(peer_id);
|
|
}
|
|
|
|
fn getPendingCountForPeerLocked(self: *DownloadManager, peer_id: [32]u8) usize {
|
|
var count: usize = 0;
|
|
for (self.pending_requests.items) |req| {
|
|
if (std.mem.eql(u8, &req.peer_id, &peer_id)) {
|
|
count += 1;
|
|
}
|
|
}
|
|
// Also count active downloads for this peer
|
|
var iter = self.active_downloads.valueIterator();
|
|
while (iter.next()) |download| {
|
|
if (std.mem.eql(u8, &download.peer_id, &peer_id)) {
|
|
count += 1;
|
|
}
|
|
}
|
|
return count;
|
|
}
|
|
|
|
/// PERF: Select the least-loaded peer for a piece
|
|
/// Returns null if no peer has the piece
|
|
pub fn selectLeastLoadedPeer(self: *DownloadManager, piece_index: u32) ?[32]u8 {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// Get all peers that have this piece
|
|
const peers_with_piece = self.peer_piece_map.getPeersForPiece(piece_index) orelse return null;
|
|
|
|
var best_peer: ?[32]u8 = null;
|
|
var min_load: usize = std.math.maxInt(usize);
|
|
|
|
var iter = peers_with_piece.iterator();
|
|
while (iter.next()) |entry| {
|
|
const peer_id = entry.key_ptr.*;
|
|
const load = self.getPendingCountForPeerLocked(peer_id);
|
|
if (load < min_load) {
|
|
min_load = load;
|
|
best_peer = peer_id;
|
|
}
|
|
}
|
|
|
|
return best_peer;
|
|
}
|
|
|
|
/// PERF: Reassign a piece from one peer to another (for load balancing)
|
|
/// Returns true if reassignment was successful
|
|
pub fn reassignPiece(self: *DownloadManager, piece_index: u32, new_peer_id: [32]u8) bool {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// Only reassign if piece is still pending (not active or completed)
|
|
var found_idx: ?usize = null;
|
|
for (self.pending_requests.items, 0..) |req, i| {
|
|
if (req.piece_index == piece_index) {
|
|
found_idx = i;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (found_idx) |idx| {
|
|
// Update the peer_id for this request
|
|
self.pending_requests.items[idx].peer_id = new_peer_id;
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
/// PERF: Get load statistics for all known peers
|
|
pub fn getPeerLoads(self: *DownloadManager, allocator: std.mem.Allocator) !std.AutoHashMap([32]u8, usize) {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
var loads = std.AutoHashMap([32]u8, usize).init(allocator);
|
|
errdefer loads.deinit();
|
|
|
|
// Count pending requests per peer
|
|
for (self.pending_requests.items) |req| {
|
|
const gop = try loads.getOrPut(req.peer_id);
|
|
if (!gop.found_existing) {
|
|
gop.value_ptr.* = 0;
|
|
}
|
|
gop.value_ptr.* += 1;
|
|
}
|
|
|
|
// Count active downloads per peer
|
|
var iter = self.active_downloads.valueIterator();
|
|
while (iter.next()) |download| {
|
|
const gop = try loads.getOrPut(download.peer_id);
|
|
if (!gop.found_existing) {
|
|
gop.value_ptr.* = 0;
|
|
}
|
|
gop.value_ptr.* += 1;
|
|
}
|
|
|
|
return loads;
|
|
}
|
|
|
|
/// PERF: Request piece with load balancing - either adds new request or rebalances existing
|
|
/// Returns true if the piece was assigned to this peer (either new or rebalanced)
|
|
pub fn requestPieceWithLoadBalancing(
|
|
self: *DownloadManager,
|
|
piece_index: u32,
|
|
peer_id: [32]u8,
|
|
) Error!bool {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// QUEUE LIMIT: Prevent runaway queue growth
|
|
if (self.pending_requests.items.len >= MAX_PENDING_QUEUE_SIZE) {
|
|
return Error.QueueFull;
|
|
}
|
|
|
|
// Check if piece is already complete
|
|
if (self.active_downloads.contains(piece_index)) {
|
|
return false; // Already downloading
|
|
}
|
|
|
|
const piece_info = self.selector.availability_map.get(piece_index) orelse return Error.InvalidData;
|
|
if (piece_info.is_downloaded or piece_info.is_verified) {
|
|
return false; // Already have this piece
|
|
}
|
|
|
|
// Check retry state
|
|
if (!self.canRequestPieceLocked(piece_index)) {
|
|
return false;
|
|
}
|
|
|
|
// Check if piece is already pending
|
|
var existing_idx: ?usize = null;
|
|
var existing_peer: ?[32]u8 = null;
|
|
for (self.pending_requests.items, 0..) |req, i| {
|
|
if (req.piece_index == piece_index) {
|
|
existing_idx = i;
|
|
existing_peer = req.peer_id;
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (existing_idx) |idx| {
|
|
// Piece is already pending - check if we should rebalance
|
|
const current_peer = existing_peer.?;
|
|
const current_load = self.getPendingCountForPeerLocked(current_peer);
|
|
const new_load = self.getPendingCountForPeerLocked(peer_id);
|
|
|
|
// Only rebalance if new peer has significantly less load (at least 10 fewer)
|
|
if (new_load + 10 < current_load) {
|
|
self.pending_requests.items[idx].peer_id = peer_id;
|
|
std.log.debug("Rebalanced piece {} from peer (load={}) to peer (load={})", .{ piece_index, current_load, new_load });
|
|
return true;
|
|
}
|
|
return false; // Keep existing assignment
|
|
}
|
|
|
|
// New piece - add request
|
|
const piece_offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
|
|
|
|
if (self.piece_size > std.math.maxInt(u32)) {
|
|
return Error.BufferOverflow;
|
|
}
|
|
const piece_size_u32: u32 = @intCast(self.piece_size);
|
|
|
|
const request = DownloadRequest.create(
|
|
piece_index,
|
|
piece_offset,
|
|
piece_size_u32,
|
|
.normal,
|
|
&peer_id,
|
|
) orelse {
|
|
return Error.InvalidData;
|
|
};
|
|
|
|
try self.pending_requests.append(self.allocator, request);
|
|
std.log.debug("Added piece {} to peer (queue size={})", .{ piece_index, self.pending_requests.items.len });
|
|
return true;
|
|
}
|
|
|
|
/// Write piece data directly to file
|
|
pub fn writePieceData(self: *DownloadManager, piece_index: u32, offset: u64, data: []const u8) Error!void {
|
|
// Check disk space before writing
|
|
if (self.file_path) |path| {
|
|
try file.checkDiskSpace(path, data.len);
|
|
}
|
|
|
|
if (self.file_writer) |*writer| {
|
|
// OVERFLOW FIX: Use checked arithmetic to prevent overflow
|
|
// Calculate piece_index * piece_size with overflow checking
|
|
const piece_offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
|
|
// Add offset with overflow checking
|
|
const absolute_offset = std.math.add(u64, piece_offset, offset) catch return Error.BufferOverflow;
|
|
|
|
try writer.writeAt(absolute_offset, data);
|
|
// PERF FIX: Don't flush after every piece - let OS buffer writes
|
|
// Flushing was causing synchronous disk I/O blocking the mutex
|
|
// Data integrity is still maintained by OS write-back cache
|
|
|
|
// Update state
|
|
self.state.addDownloadedBytes(data.len);
|
|
} else {
|
|
return Error.InvalidState;
|
|
}
|
|
}
|
|
|
|
/// PERF: Get info needed for mutex-free pwrite operations
|
|
/// Returns file handle and calculated absolute offset for direct pwrite
|
|
/// Call this while holding mutex, then release mutex and do pwrite directly
|
|
pub fn getWriteInfo(self: *DownloadManager, piece_index: u32, offset: u64) Error!struct { file: std.fs.File, absolute_offset: u64, file_path: []const u8 } {
|
|
const writer = self.file_writer orelse return Error.InvalidState;
|
|
const path = self.file_path orelse return Error.FileError;
|
|
|
|
// Calculate absolute offset with overflow checking
|
|
const piece_offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
|
|
const absolute_offset = std.math.add(u64, piece_offset, offset) catch return Error.BufferOverflow;
|
|
|
|
return .{
|
|
.file = writer.getFileHandle(),
|
|
.absolute_offset = absolute_offset,
|
|
.file_path = path,
|
|
};
|
|
}
|
|
|
|
/// PERF: Update download bytes count (call after mutex-free pwrite)
|
|
pub fn addDownloadedBytesExternal(self: *DownloadManager, bytes: usize) void {
|
|
self.state.addDownloadedBytes(bytes);
|
|
}
|
|
|
|
/// Verify a piece against expected hash by reading from disk
|
|
pub fn verifyPiece(self: *DownloadManager, piece_index: u32, expected_hash: *const PieceHash) Error!bool {
|
|
// Get file path
|
|
const file_path = self.file_path orelse return Error.FileError;
|
|
|
|
// Validate path before reading
|
|
if (!path_security.PathValidator.isPathSafe(file_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// Calculate piece offset and size
|
|
// OVERFLOW FIX: Use checked multiplication for offset calculation
|
|
const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
|
|
const actual_piece_size = @min(self.piece_size, self.total_size - offset);
|
|
|
|
// Open file for reading
|
|
var piece_file = std.fs.cwd().openFile(file_path, .{}) catch return Error.FileError;
|
|
defer piece_file.close();
|
|
|
|
// Seek to piece position
|
|
piece_file.seekTo(offset) catch return Error.FileError;
|
|
|
|
// Read piece data
|
|
const data = self.allocator.alloc(u8, actual_piece_size) catch return Error.OutOfMemory;
|
|
defer self.allocator.free(data);
|
|
|
|
const bytes_read = piece_file.readAll(data) catch return Error.FileError;
|
|
if (bytes_read != actual_piece_size) {
|
|
return Error.FileError;
|
|
}
|
|
|
|
// Calculate hash of the data
|
|
var actual_hash: [32]u8 = undefined;
|
|
std.crypto.hash.sha2.Sha256.hash(data, &actual_hash, .{});
|
|
|
|
// Compare with expected hash (timing-safe comparison)
|
|
return std.crypto.timing_safe.eql([32]u8, actual_hash, expected_hash.*);
|
|
}
|
|
|
|
/// Check if we have a specific piece
|
|
pub fn hasPiece(self: *const DownloadManager, piece_index: u32) bool {
|
|
if (self.selector.availability_map.get(piece_index)) |piece_avail| {
|
|
return piece_avail.is_downloaded;
|
|
}
|
|
return false;
|
|
}
|
|
|
|
/// Get all known peers that we're downloading from
|
|
/// CASCADE FIX: Used to broadcast "have" messages when we acquire new pieces
|
|
pub fn getKnownPeers(self: *DownloadManager, out_peers: [][32]u8) usize {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
var peer_iter = self.peer_piece_map.getAllPeers();
|
|
var count: usize = 0;
|
|
while (peer_iter.next()) |peer_id| {
|
|
if (count < out_peers.len) {
|
|
out_peers[count] = peer_id.*;
|
|
count += 1;
|
|
}
|
|
}
|
|
return count;
|
|
}
|
|
|
|
/// Get the count of known peers
|
|
pub fn getKnownPeerCount(self: *DownloadManager) usize {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
return self.peer_piece_map.getPeerCount();
|
|
}
|
|
|
|
// ============================================================
|
|
// Resume State Persistence
|
|
// ============================================================
|
|
|
|
/// Resume state header - stored at the beginning of the .resume file
|
|
pub const ResumeStateHeader = extern struct {
|
|
/// Magic bytes to identify valid resume file
|
|
magic: [8]u8 = .{ 'Z', 'I', 'G', 'P', '2', 'P', 'R', 'S' },
|
|
/// Version number for forward compatibility
|
|
version: u32 = 1,
|
|
/// Total file size being downloaded
|
|
total_size: u64,
|
|
/// Size of each piece
|
|
piece_size: u64,
|
|
/// Number of pieces
|
|
piece_count: u32,
|
|
/// Number of completed pieces
|
|
completed_count: u32,
|
|
/// SHA-256 hash of the target file (for verification)
|
|
file_hash: [32]u8,
|
|
/// Reserved for future use
|
|
_reserved: [32]u8 = [_]u8{0} ** 32,
|
|
};
|
|
|
|
/// Save current download state to a resume file
|
|
/// The resume file stores which pieces are completed, allowing downloads to continue after restart
|
|
pub fn saveResumeState(self: *DownloadManager, resume_path: []const u8) Error!void {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
// Validate path
|
|
if (!path_security.PathValidator.isPathSafe(resume_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// Create resume file
|
|
var resume_file = std.fs.cwd().createFile(resume_path, .{}) catch return Error.FileError;
|
|
defer resume_file.close();
|
|
|
|
// Build header
|
|
var header = ResumeStateHeader{
|
|
.total_size = self.total_size,
|
|
.piece_size = self.piece_size,
|
|
.piece_count = self.state.piece_count,
|
|
.completed_count = self.state.completed_pieces.load(.acquire),
|
|
.file_hash = [_]u8{0} ** 32, // TODO: Store actual file hash if available
|
|
};
|
|
|
|
// Write header
|
|
const header_bytes = std.mem.asBytes(&header);
|
|
resume_file.writeAll(header_bytes) catch return Error.FileError;
|
|
|
|
// Build and write bitfield (1 bit per piece, packed into bytes)
|
|
const bitfield_size = (self.state.piece_count + 7) / 8;
|
|
const bitfield = self.allocator.alloc(u8, bitfield_size) catch return Error.OutOfMemory;
|
|
defer self.allocator.free(bitfield);
|
|
@memset(bitfield, 0);
|
|
|
|
// Set bits for completed pieces
|
|
var iter = self.selector.availability_map.iterator();
|
|
while (iter.next()) |entry| {
|
|
if (entry.value_ptr.is_downloaded or entry.value_ptr.is_verified) {
|
|
const piece_idx = entry.key_ptr.*;
|
|
const byte_idx = piece_idx / 8;
|
|
const bit_idx: u3 = @intCast(piece_idx % 8);
|
|
if (byte_idx < bitfield.len) {
|
|
bitfield[byte_idx] |= (@as(u8, 1) << bit_idx);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Write bitfield
|
|
resume_file.writeAll(bitfield) catch return Error.FileError;
|
|
|
|
std.log.info("Resume state saved: {}/{} pieces completed", .{
|
|
header.completed_count,
|
|
header.piece_count,
|
|
});
|
|
}
|
|
|
|
/// Load resume state and create a DownloadManager configured to continue the download
|
|
/// Returns null if the resume file is invalid or doesn't match expected parameters
|
|
pub fn loadResumeState(
|
|
allocator: mem.Allocator,
|
|
resume_path: []const u8,
|
|
expected_total_size: u64,
|
|
expected_piece_size: u64,
|
|
strategy: SelectionStrategy,
|
|
) Error!?DownloadManager {
|
|
// Validate path
|
|
if (!path_security.PathValidator.isPathSafe(resume_path)) {
|
|
return Error.InvalidData;
|
|
}
|
|
|
|
// Open resume file
|
|
var resume_file = std.fs.cwd().openFile(resume_path, .{}) catch return null;
|
|
defer resume_file.close();
|
|
|
|
// Read header
|
|
var header_bytes: [@sizeOf(ResumeStateHeader)]u8 = undefined;
|
|
const header_read = resume_file.readAll(&header_bytes) catch return null;
|
|
if (header_read != @sizeOf(ResumeStateHeader)) {
|
|
std.log.warn("Resume file header too small", .{});
|
|
return null;
|
|
}
|
|
|
|
const header: *const ResumeStateHeader = @ptrCast(@alignCast(&header_bytes));
|
|
|
|
// Validate magic
|
|
const expected_magic = [_]u8{ 'Z', 'I', 'G', 'P', '2', 'P', 'R', 'S' };
|
|
if (!std.mem.eql(u8, &header.magic, &expected_magic)) {
|
|
std.log.warn("Resume file has invalid magic", .{});
|
|
return null;
|
|
}
|
|
|
|
// Validate version
|
|
if (header.version != 1) {
|
|
std.log.warn("Resume file version {} not supported", .{header.version});
|
|
return null;
|
|
}
|
|
|
|
// Validate parameters match
|
|
if (header.total_size != expected_total_size or header.piece_size != expected_piece_size) {
|
|
std.log.warn("Resume file parameters don't match: expected size={} piece_size={}, got size={} piece_size={}", .{
|
|
expected_total_size,
|
|
expected_piece_size,
|
|
header.total_size,
|
|
header.piece_size,
|
|
});
|
|
return null;
|
|
}
|
|
|
|
// Create download manager
|
|
var manager = try DownloadManager.init(
|
|
header.total_size,
|
|
header.piece_count,
|
|
strategy,
|
|
header.piece_size,
|
|
allocator,
|
|
);
|
|
errdefer manager.deinit();
|
|
|
|
// Read bitfield
|
|
const bitfield_size = (header.piece_count + 7) / 8;
|
|
const bitfield = allocator.alloc(u8, bitfield_size) catch return Error.OutOfMemory;
|
|
defer allocator.free(bitfield);
|
|
|
|
const bitfield_read = resume_file.readAll(bitfield) catch {
|
|
std.log.warn("Failed to read resume bitfield", .{});
|
|
return null;
|
|
};
|
|
if (bitfield_read != bitfield_size) {
|
|
std.log.warn("Resume bitfield truncated", .{});
|
|
return null;
|
|
}
|
|
|
|
// Mark completed pieces
|
|
var restored_count: u32 = 0;
|
|
var piece_idx: u32 = 0;
|
|
while (piece_idx < header.piece_count) : (piece_idx += 1) {
|
|
const byte_idx = piece_idx / 8;
|
|
const bit_idx: u3 = @intCast(piece_idx % 8);
|
|
if (byte_idx < bitfield.len) {
|
|
const is_complete = (bitfield[byte_idx] & (@as(u8, 1) << bit_idx)) != 0;
|
|
if (is_complete) {
|
|
// Add piece to selector and mark as downloaded
|
|
try manager.selector.addPiece(piece_idx, 0);
|
|
if (manager.selector.availability_map.getPtr(piece_idx)) |avail| {
|
|
avail.is_downloaded = true;
|
|
avail.is_verified = true;
|
|
}
|
|
_ = manager.state.completed_pieces.fetchAdd(1, .release);
|
|
restored_count += 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
std.log.info("Resume state loaded: {}/{} pieces restored", .{
|
|
restored_count,
|
|
header.piece_count,
|
|
});
|
|
|
|
return manager;
|
|
}
|
|
|
|
/// Verify pieces that are marked as complete by reading from disk and checking hashes
|
|
/// This should be called after loadResumeState to validate the partial download
|
|
/// Returns the number of pieces that failed verification (and were reset to incomplete)
|
|
pub fn verifyExistingPieces(
|
|
self: *DownloadManager,
|
|
piece_hashes: []const PieceHash,
|
|
) Error!u32 {
|
|
self.manager_mutex.lock();
|
|
defer self.manager_mutex.unlock();
|
|
|
|
const file_path = self.file_path orelse return Error.FileError;
|
|
|
|
// Open file for reading
|
|
var data_file = std.fs.cwd().openFile(file_path, .{}) catch return Error.FileError;
|
|
defer data_file.close();
|
|
|
|
var failed_count: u32 = 0;
|
|
var verified_count: u32 = 0;
|
|
|
|
// Allocate buffer for reading pieces (reuse for all pieces)
|
|
const buffer = self.allocator.alloc(u8, self.piece_size) catch return Error.OutOfMemory;
|
|
defer self.allocator.free(buffer);
|
|
|
|
var iter = self.selector.availability_map.iterator();
|
|
while (iter.next()) |entry| {
|
|
const piece_idx = entry.key_ptr.*;
|
|
const avail = entry.value_ptr;
|
|
|
|
// Only verify pieces marked as complete
|
|
if (!avail.is_downloaded and !avail.is_verified) {
|
|
continue;
|
|
}
|
|
|
|
// Bounds check
|
|
if (piece_idx >= piece_hashes.len) {
|
|
avail.is_downloaded = false;
|
|
avail.is_verified = false;
|
|
failed_count += 1;
|
|
continue;
|
|
}
|
|
|
|
// Calculate offset and size
|
|
const offset = std.math.mul(u64, piece_idx, self.piece_size) catch {
|
|
avail.is_downloaded = false;
|
|
avail.is_verified = false;
|
|
failed_count += 1;
|
|
continue;
|
|
};
|
|
const actual_size = @min(self.piece_size, self.total_size -| offset);
|
|
|
|
// Seek and read
|
|
data_file.seekTo(offset) catch {
|
|
avail.is_downloaded = false;
|
|
avail.is_verified = false;
|
|
failed_count += 1;
|
|
continue;
|
|
};
|
|
|
|
const bytes_read = data_file.readAll(buffer[0..actual_size]) catch {
|
|
avail.is_downloaded = false;
|
|
avail.is_verified = false;
|
|
failed_count += 1;
|
|
continue;
|
|
};
|
|
|
|
if (bytes_read != actual_size) {
|
|
avail.is_downloaded = false;
|
|
avail.is_verified = false;
|
|
failed_count += 1;
|
|
continue;
|
|
}
|
|
|
|
// Calculate and compare hash
|
|
var actual_hash: [32]u8 = undefined;
|
|
std.crypto.hash.sha2.Sha256.hash(buffer[0..actual_size], &actual_hash, .{});
|
|
|
|
if (!std.crypto.timing_safe.eql([32]u8, actual_hash, piece_hashes[piece_idx])) {
|
|
// Hash mismatch - mark as incomplete
|
|
avail.is_downloaded = false;
|
|
avail.is_verified = false;
|
|
_ = self.state.completed_pieces.fetchSub(1, .release);
|
|
failed_count += 1;
|
|
std.log.warn("Resume verification: piece {} hash mismatch", .{piece_idx});
|
|
} else {
|
|
verified_count += 1;
|
|
}
|
|
}
|
|
|
|
std.log.info("Resume verification complete: {} verified, {} failed", .{
|
|
verified_count,
|
|
failed_count,
|
|
});
|
|
|
|
return failed_count;
|
|
}
|
|
|
|
/// Delete the resume state file (call after successful download completion)
|
|
pub fn deleteResumeState(resume_path: []const u8) void {
|
|
std.fs.cwd().deleteFile(resume_path) catch |err| {
|
|
std.log.debug("Failed to delete resume file: {}", .{err});
|
|
};
|
|
}
|
|
};
|
|
|
|
/// Piece retry tracking
|
|
/// MEM-2 FIX: Changed last_peer from slice to owned array to prevent dangling pointer
|
|
/// CRIT-8 FIX: Changed last_failure_reason from slice to owned array to prevent dangling pointer
|
|
pub const PieceRetryTracker = struct {
|
|
retry_count: u8,
|
|
last_attempt: i64,
|
|
/// MEM-2 FIX: Store owned copy of peer ID instead of non-owning slice
|
|
last_peer: ?[32]u8,
|
|
/// CRIT-8 FIX: Store the last failure reason in owned storage
|
|
/// Using fixed-size array to prevent dangling pointer when reason goes out of scope
|
|
last_failure_reason_buf: [128]u8,
|
|
last_failure_reason_len: u8,
|
|
|
|
/// Maximum retry attempts per piece before marking as permanently failed.
|
|
/// Increased from 3 to 10 following BitTorrent best practices - allows
|
|
/// recovery during temporary seeder outages (e.g., seeder goes offline
|
|
/// for 10+ seconds then comes back).
|
|
pub const MAX_RETRIES: u8 = 10;
|
|
|
|
/// Base retry delay in milliseconds. Using 500ms for faster failover.
|
|
/// With exponential backoff: 500ms, 1s, 2s, 4s, 8s, 16s, 32s, 64s, 128s, 256s
|
|
/// Total time before permanent failure: ~8.5 minutes
|
|
pub const BASE_RETRY_DELAY_MS: i64 = 500;
|
|
|
|
pub fn init() PieceRetryTracker {
|
|
return PieceRetryTracker{
|
|
.retry_count = 0,
|
|
.last_attempt = 0,
|
|
.last_peer = null,
|
|
// CRIT-8 FIX: Initialize with empty reason buffer
|
|
.last_failure_reason_buf = [_]u8{0} ** 128,
|
|
.last_failure_reason_len = 0,
|
|
};
|
|
}
|
|
|
|
pub fn shouldRetry(self: *const PieceRetryTracker) bool {
|
|
return self.retry_count < MAX_RETRIES;
|
|
}
|
|
|
|
pub fn getRetryDelay(self: *const PieceRetryTracker) i64 {
|
|
// Exponential backoff: 1s, 2s, 4s, capped at 2^30 ms (~12 days)
|
|
// MED-1 FIX: Clamp shift to prevent overflow (max safe shift is 62)
|
|
const clamped_count: u6 = @intCast(@min(self.retry_count, 30));
|
|
return BASE_RETRY_DELAY_MS * (@as(i64, 1) << clamped_count);
|
|
}
|
|
|
|
/// Record a failure from a peer
|
|
/// MEM-2 FIX: Copies peer ID instead of storing reference
|
|
pub fn recordFailure(self: *PieceRetryTracker, peer: []const u8) void {
|
|
self.retry_count += 1;
|
|
self.last_attempt = std.time.milliTimestamp();
|
|
// Copy peer ID to owned array - prevents dangling pointer
|
|
if (peer.len >= 32) {
|
|
var peer_copy: [32]u8 = undefined;
|
|
@memcpy(&peer_copy, peer[0..32]);
|
|
self.last_peer = peer_copy;
|
|
} else {
|
|
// Pad shorter peer IDs with zeros
|
|
var peer_copy: [32]u8 = [_]u8{0} ** 32;
|
|
@memcpy(peer_copy[0..peer.len], peer);
|
|
self.last_peer = peer_copy;
|
|
}
|
|
}
|
|
|
|
/// Get the last peer ID as a slice (safe - points to owned data)
|
|
pub fn getLastPeer(self: *const PieceRetryTracker) ?[]const u8 {
|
|
if (self.last_peer) |*peer| {
|
|
return peer[0..];
|
|
}
|
|
return null;
|
|
}
|
|
|
|
pub fn canRetryNow(self: *const PieceRetryTracker) bool {
|
|
if (!self.shouldRetry()) return false;
|
|
if (self.retry_count == 0) return true;
|
|
|
|
const now = std.time.milliTimestamp();
|
|
const delay = self.getRetryDelay();
|
|
return (now - self.last_attempt) >= delay;
|
|
}
|
|
|
|
pub fn reset(self: *PieceRetryTracker) void {
|
|
self.retry_count = 0;
|
|
self.last_attempt = 0;
|
|
self.last_peer = null;
|
|
// CRIT-8 FIX: Reset failure reason buffer
|
|
self.last_failure_reason_len = 0;
|
|
@memset(&self.last_failure_reason_buf, 0);
|
|
}
|
|
|
|
/// CRIT-8 FIX: Set the last failure reason, copying to owned storage
|
|
pub fn setLastFailureReason(self: *PieceRetryTracker, reason: []const u8) void {
|
|
const copy_len = @min(reason.len, self.last_failure_reason_buf.len);
|
|
@memcpy(self.last_failure_reason_buf[0..copy_len], reason[0..copy_len]);
|
|
self.last_failure_reason_len = @intCast(copy_len);
|
|
}
|
|
|
|
/// CRIT-8 FIX: Get the last failure reason (returns slice to owned buffer)
|
|
pub fn getLastFailureReason(self: *const PieceRetryTracker) []const u8 {
|
|
return self.last_failure_reason_buf[0..self.last_failure_reason_len];
|
|
}
|
|
};
|
|
|
|
/// Active download tracking
|
|
/// CRIT-2 FIX: Changed peer_id from []const u8 to [32]u8 to prevent dangling pointer
|
|
/// The previous implementation stored a slice pointing to DownloadRequest.peer_id,
|
|
/// which became invalid after the request was removed from pending_requests.
|
|
pub const ActiveDownload = struct {
|
|
piece_index: u32,
|
|
/// CRIT-2 FIX: Owned array instead of slice to prevent use-after-free
|
|
peer_id: [32]u8,
|
|
offset: u64,
|
|
length: u32,
|
|
downloaded_bytes: u32,
|
|
started_at: i64,
|
|
status: DownloadStatus,
|
|
|
|
pub const DownloadStatus = enum(u8) {
|
|
downloading = 1,
|
|
verifying = 2,
|
|
completed = 3,
|
|
failed = 4,
|
|
};
|
|
|
|
/// Get peer ID as slice for compatibility with existing code
|
|
pub fn getPeerId(self: *const ActiveDownload) []const u8 {
|
|
return &self.peer_id;
|
|
}
|
|
};
|
|
|
|
/// Piece retry information
|
|
pub const PieceRetryInfo = struct {
|
|
retry_count: u8,
|
|
can_retry: bool,
|
|
next_retry_ms: i64,
|
|
last_attempt_ms: i64,
|
|
};
|
|
|
|
/// Download statistics
|
|
pub const DownloadStats = struct {
|
|
state: DownloadState,
|
|
pending_requests: usize,
|
|
active_downloads: usize,
|
|
progress: f32,
|
|
speed: f32,
|
|
time_remaining: i64,
|
|
retrying_pieces: u32,
|
|
permanently_failed: u32,
|
|
|
|
/// Get formatted progress string
|
|
/// MEM-M4 FIX: Properly free intermediate time_str allocation
|
|
pub fn getProgressString(self: DownloadStats, allocator: mem.Allocator) Error![]u8 {
|
|
const downloaded_mb = @as(f32, @floatFromInt(self.state.downloaded_bytes.load(.monotonic))) / (1024 * 1024);
|
|
const total_mb = @as(f32, @floatFromInt(self.state.total_size)) / (1024 * 1024);
|
|
|
|
const speed_mbps = self.speed / (1024 * 1024);
|
|
|
|
// MEM-M4 FIX: Track whether we need to free time_str
|
|
var time_str_allocated: ?[]u8 = null;
|
|
defer if (time_str_allocated) |s| allocator.free(s);
|
|
|
|
var time_str: []const u8 = "unknown";
|
|
if (self.time_remaining > 0) {
|
|
const hours = @divTrunc(self.time_remaining, 3600);
|
|
const minutes = @divTrunc(@mod(self.time_remaining, 3600), 60);
|
|
const seconds = @mod(self.time_remaining, 60);
|
|
|
|
time_str_allocated = try fmt.allocPrint(allocator, "{d}:{d:0>2}:{d:0>2}", .{ hours, minutes, seconds });
|
|
time_str = time_str_allocated.?;
|
|
}
|
|
|
|
return fmt.allocPrint(
|
|
allocator,
|
|
"{d:.1}/{d:.1} MB ({d:.1}%) - {d:.1} MB/s - {s} remaining",
|
|
.{
|
|
downloaded_mb,
|
|
total_mb,
|
|
self.progress * 100,
|
|
speed_mbps,
|
|
time_str,
|
|
},
|
|
);
|
|
}
|
|
};
|
|
|
|
/// Download configuration
|
|
/// Defaults are read from the centralized core.limits configuration
|
|
pub const DownloadConfig = struct {
|
|
max_concurrent_downloads: usize,
|
|
piece_size: u64,
|
|
request_timeout: i64,
|
|
max_requests_per_peer: usize,
|
|
min_piece_priority: PieceAvailability.Priority,
|
|
|
|
pub fn default() DownloadConfig {
|
|
return DownloadConfig{
|
|
.max_concurrent_downloads = core.limits.defaults.file.max_concurrent_downloads,
|
|
.piece_size = core.limits.defaults.file.piece_size,
|
|
.request_timeout = 30,
|
|
.max_requests_per_peer = core.limits.defaults.file.max_download_requests_per_peer,
|
|
.min_piece_priority = .low,
|
|
};
|
|
}
|
|
};
|
|
|
|
/// Download queue for managing multiple downloads
|
|
pub const DownloadQueue = struct {
|
|
downloads: std.ArrayList(DownloadManager),
|
|
allocator: mem.Allocator,
|
|
|
|
pub fn init(allocator: mem.Allocator) DownloadQueue {
|
|
return DownloadQueue{
|
|
.downloads = .{},
|
|
.allocator = allocator,
|
|
};
|
|
}
|
|
|
|
pub fn deinit(self: *DownloadQueue) void {
|
|
for (self.downloads.items) |*download| {
|
|
download.deinit();
|
|
}
|
|
self.downloads.deinit(self.allocator);
|
|
}
|
|
|
|
/// Add new download
|
|
pub fn addDownload(
|
|
self: *DownloadQueue,
|
|
total_size: u64,
|
|
piece_count: u32,
|
|
strategy: SelectionStrategy,
|
|
piece_size: u64,
|
|
) Error!*DownloadManager {
|
|
const download = try self.downloads.addOne(self.allocator);
|
|
download.* = try DownloadManager.init(total_size, piece_count, strategy, piece_size, self.allocator);
|
|
return download;
|
|
}
|
|
|
|
/// Process all downloads
|
|
pub fn processAll(self: *DownloadQueue, config: DownloadConfig) Error!void {
|
|
for (self.downloads.items) |*download| {
|
|
try download.processRequests(config.max_concurrent_downloads);
|
|
}
|
|
}
|
|
|
|
/// Get combined statistics
|
|
pub fn getCombinedStats(self: *DownloadQueue) CombinedDownloadStats {
|
|
var total_downloaded: u64 = 0;
|
|
var total_size: u64 = 0;
|
|
var total_pieces: u32 = 0;
|
|
var completed_pieces: u32 = 0;
|
|
var active_downloads: usize = 0;
|
|
|
|
for (self.downloads.items) |*dl| {
|
|
const stats = dl.getStats();
|
|
total_downloaded += stats.state.downloaded_bytes.load(.monotonic);
|
|
total_size += stats.state.total_size;
|
|
total_pieces += stats.state.piece_count;
|
|
completed_pieces += stats.state.completed_pieces.load(.monotonic);
|
|
active_downloads += stats.active_downloads;
|
|
}
|
|
|
|
return CombinedDownloadStats{
|
|
.total_downloaded = total_downloaded,
|
|
.total_size = total_size,
|
|
.total_pieces = total_pieces,
|
|
.completed_pieces = completed_pieces,
|
|
.active_downloads = active_downloads,
|
|
};
|
|
}
|
|
|
|
/// Check if all downloads are complete
|
|
pub fn areAllComplete(self: *DownloadQueue) bool {
|
|
for (self.downloads.items) |download| {
|
|
if (!download.isComplete()) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
};
|
|
|
|
/// Combined download statistics
|
|
pub const CombinedDownloadStats = struct {
|
|
total_downloaded: u64,
|
|
total_size: u64,
|
|
total_pieces: u32,
|
|
completed_pieces: u32,
|
|
active_downloads: usize,
|
|
|
|
/// Get overall progress
|
|
pub fn getProgress(self: CombinedDownloadStats) f32 {
|
|
if (self.total_size == 0) return 0.0;
|
|
return @as(f32, @floatFromInt(self.total_downloaded)) / @as(f32, @floatFromInt(self.total_size));
|
|
}
|
|
|
|
/// Get completion percentage
|
|
pub fn getCompletionPercent(self: CombinedDownloadStats) f32 {
|
|
if (self.total_pieces == 0) return 0.0;
|
|
return @as(f32, @floatFromInt(self.completed_pieces)) / @as(f32, @floatFromInt(self.total_pieces)) * 100.0;
|
|
}
|
|
};
|
|
|
|
// Testing functions
|
|
test "download state operations" {
|
|
const total_size: u64 = 1000;
|
|
const piece_count: u32 = 10;
|
|
var state = DownloadState.init(total_size, piece_count);
|
|
|
|
try testing.expectEqual(@as(f32, 0.0), state.getProgress());
|
|
try testing.expect(!state.isComplete());
|
|
try testing.expectEqual(@as(f32, 0.0), state.getCompletionPercent());
|
|
|
|
// Add some downloaded data
|
|
state.addDownloadedBytes(250);
|
|
state.addVerifiedBytes(250);
|
|
|
|
try testing.expectEqual(@as(f32, 0.25), state.getProgress());
|
|
try testing.expectEqual(@as(f32, 0.25), state.getVerificationProgress());
|
|
|
|
// Mark pieces as completed
|
|
state.markPieceCompleted();
|
|
try testing.expectEqual(@as(u32, 1), state.completed_pieces.load(.monotonic));
|
|
try testing.expectEqual(@as(f32, 10.0), state.getCompletionPercent());
|
|
}
|
|
|
|
test "download request operations" {
|
|
const peer_id = "peer123";
|
|
// MEM-M3: Now returns optional due to validation
|
|
var request = DownloadRequest.create(0, 0, 1024, .normal, peer_id) orelse {
|
|
try testing.expect(false); // Should not fail with valid params
|
|
return;
|
|
};
|
|
|
|
try testing.expectEqual(@as(u32, 0), request.piece_index);
|
|
try testing.expectEqual(@as(u64, 0), request.offset);
|
|
try testing.expectEqual(@as(u32, 1024), request.length);
|
|
try testing.expectEqual(PieceAvailability.Priority.normal, request.priority);
|
|
|
|
// Test expiration - a fresh request with any timeout is not expired
|
|
const is_not_expired = !request.isExpired(60); // 60 second timeout
|
|
try testing.expect(is_not_expired);
|
|
|
|
// For a request to be expired, time since creation must exceed timeout
|
|
// isExpired returns (now - requested_at > timeout)
|
|
// With timeout = 0, a freshly created request returns false since 0 > 0 is false
|
|
}
|
|
|
|
test "download manager basic operations" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Verify manager starts empty
|
|
try testing.expectEqual(@as(usize, 0), manager.pending_requests.items.len);
|
|
try testing.expectEqual(@as(usize, 0), manager.active_downloads.count());
|
|
|
|
// Add peer with available pieces - this adds pieces to selector
|
|
const peer_id = "test_peer";
|
|
const available_pieces = [_]u32{ 0, 1, 2, 3, 4 };
|
|
try manager.addPeer(peer_id, &available_pieces);
|
|
|
|
// Verify piece 0 is in selector after addPeer
|
|
const piece_info = manager.selector.availability_map.get(0);
|
|
try testing.expect(piece_info != null);
|
|
try testing.expect(!piece_info.?.is_downloaded);
|
|
try testing.expect(!piece_info.?.is_verified);
|
|
|
|
// Request a piece - this should add to pending queue
|
|
try manager.requestPiece(0, .high, peer_id);
|
|
|
|
// After requestPiece, pending should have 1 item
|
|
const pending_count = manager.pending_requests.items.len;
|
|
try testing.expectEqual(@as(usize, 1), pending_count);
|
|
|
|
// Process requests - moves from pending to active
|
|
try manager.processRequests(1);
|
|
try testing.expectEqual(@as(usize, 0), manager.pending_requests.items.len);
|
|
try testing.expectEqual(@as(usize, 1), manager.active_downloads.count());
|
|
|
|
// Get statistics - should reflect processed state
|
|
const stats = manager.getStats();
|
|
try testing.expectEqual(@as(usize, 1), stats.active_downloads);
|
|
try testing.expectEqual(@as(usize, 0), stats.pending_requests); // Fixed: was incorrectly expecting 1
|
|
}
|
|
|
|
test "download manager piece data handling" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Set up output file
|
|
const test_file = "test_download.bin";
|
|
try manager.setOutputFile(test_file);
|
|
|
|
// Add peer and request piece
|
|
const available_pieces = [_]u32{ 0 };
|
|
try manager.addPeer("peer1", &available_pieces);
|
|
|
|
// Create test piece data
|
|
const test_data = "Test piece data for download";
|
|
const piece_hash = try HashUtils.sha256(test_data);
|
|
|
|
// Handle piece data
|
|
try manager.handlePieceData(0, test_data, piece_hash);
|
|
|
|
// Check state updates
|
|
try testing.expectEqual(@as(u32, 1), manager.state.completed_pieces.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, test_data.len), manager.state.downloaded_bytes.load(.monotonic));
|
|
try testing.expectEqual(@as(u32, test_data.len), manager.state.verified_bytes.load(.monotonic));
|
|
|
|
// Clean up test file
|
|
std.fs.cwd().deleteFile(test_file) catch {};
|
|
}
|
|
|
|
test "download queue operations" {
|
|
const allocator = testing.allocator;
|
|
var queue = DownloadQueue.init(allocator);
|
|
defer queue.deinit();
|
|
|
|
// Add multiple downloads
|
|
_ = try queue.addDownload(1000, 10, .rarest_first, 100);
|
|
_ = try queue.addDownload(2000, 20, .sequential, 100);
|
|
|
|
try testing.expectEqual(@as(usize, 2), queue.downloads.items.len);
|
|
|
|
// Get combined stats
|
|
const combined = queue.getCombinedStats();
|
|
try testing.expectEqual(@as(u64, 3000), combined.total_size);
|
|
try testing.expectEqual(@as(u32, 30), combined.total_pieces);
|
|
try testing.expectEqual(@as(f32, 0.0), combined.getProgress());
|
|
try testing.expect(!queue.areAllComplete());
|
|
}
|
|
|
|
test "download stats formatting" {
|
|
const allocator = testing.allocator;
|
|
var state = DownloadState.init(1024 * 1024, 10); // 1MB file
|
|
state.addDownloadedBytes(512 * 1024); // 512KB downloaded
|
|
|
|
const stats = DownloadStats{
|
|
.state = state,
|
|
.pending_requests = 2,
|
|
.active_downloads = 1,
|
|
.progress = 0.5,
|
|
.speed = 1024 * 100, // 100 KB/s
|
|
.time_remaining = 3600, // 1 hour
|
|
.retrying_pieces = 0,
|
|
.permanently_failed = 0,
|
|
};
|
|
|
|
const progress_str = try stats.getProgressString(allocator);
|
|
defer allocator.free(progress_str);
|
|
|
|
try testing.expect(progress_str.len > 0);
|
|
try testing.expect(std.mem.indexOf(u8, progress_str, "MB") != null);
|
|
}
|
|
|
|
test "verifyPiece actually verifies hash" {
|
|
const allocator = testing.allocator;
|
|
|
|
// Create a temporary file with known content
|
|
const test_file = "test_verify_piece.bin";
|
|
const test_data = "This is test data for piece verification";
|
|
|
|
// Create test file - use writeAll to ensure all bytes written
|
|
const test_file_handle = std.fs.cwd().createFile(test_file, .{}) catch return;
|
|
test_file_handle.writeAll(test_data) catch return;
|
|
test_file_handle.close();
|
|
|
|
// Calculate expected hash
|
|
const expected_hash = try HashUtils.sha256(test_data);
|
|
|
|
// Create wrong hash for testing
|
|
var wrong_hash: [32]u8 = undefined;
|
|
std.crypto.hash.sha2.Sha256.hash("wrong data", &wrong_hash, .{});
|
|
|
|
// Setup download manager
|
|
var manager = try DownloadManager.init(test_data.len, 1, .sequential, test_data.len, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Set file_path directly - don't use setOutputFile which truncates the file
|
|
manager.file_path = try allocator.dupe(u8, test_file);
|
|
|
|
// Verify piece returns true for correct hash
|
|
const valid = try manager.verifyPiece(0, &expected_hash);
|
|
try testing.expect(valid);
|
|
|
|
// Verify piece returns false for wrong hash
|
|
const invalid = try manager.verifyPiece(0, &wrong_hash);
|
|
try testing.expect(!invalid);
|
|
|
|
// Clean up
|
|
std.fs.cwd().deleteFile(test_file) catch |err| {
|
|
std.log.warn("Failed to cleanup test file {s}: {}", .{ test_file, err });
|
|
};
|
|
}
|
|
|
|
test "piece retry tracker operations" {
|
|
var tracker = PieceRetryTracker.init();
|
|
|
|
// Initial state
|
|
try testing.expectEqual(@as(u8, 0), tracker.retry_count);
|
|
try testing.expect(tracker.shouldRetry());
|
|
try testing.expect(tracker.canRetryNow());
|
|
|
|
// Record first failure - exponential backoff: 500ms * 2^1 = 1000ms
|
|
tracker.recordFailure("peer1");
|
|
try testing.expectEqual(@as(u8, 1), tracker.retry_count);
|
|
try testing.expect(tracker.shouldRetry());
|
|
try testing.expectEqual(@as(i64, 1000), tracker.getRetryDelay());
|
|
|
|
// Record second failure - 500ms * 2^2 = 2000ms
|
|
tracker.recordFailure("peer2");
|
|
try testing.expectEqual(@as(u8, 2), tracker.retry_count);
|
|
try testing.expect(tracker.shouldRetry());
|
|
try testing.expectEqual(@as(i64, 2000), tracker.getRetryDelay());
|
|
|
|
// Record failures until MAX_RETRIES (10)
|
|
// We've recorded 2 failures, need 8 more to reach 10
|
|
var i: u8 = 3;
|
|
while (i <= PieceRetryTracker.MAX_RETRIES) : (i += 1) {
|
|
tracker.recordFailure("peerN");
|
|
}
|
|
try testing.expectEqual(PieceRetryTracker.MAX_RETRIES, tracker.retry_count);
|
|
try testing.expect(!tracker.shouldRetry()); // Max retries reached
|
|
|
|
// Reset tracker
|
|
tracker.reset();
|
|
try testing.expectEqual(@as(u8, 0), tracker.retry_count);
|
|
try testing.expect(tracker.shouldRetry());
|
|
}
|
|
|
|
test "download manager retry logic" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Add peer with available pieces
|
|
const peer_id = "test_peer";
|
|
const available_pieces = [_]u32{ 0, 1, 2 };
|
|
try manager.addPeer(peer_id, &available_pieces);
|
|
|
|
// Request a piece
|
|
try manager.requestPiece(0, .high, peer_id);
|
|
try manager.processRequests(1);
|
|
|
|
// Simulate download failure
|
|
try manager.handleDownloadFailure(0, "Network timeout");
|
|
|
|
// Check retry tracker was created
|
|
const retry_info = manager.getPieceRetryInfo(0);
|
|
try testing.expect(retry_info != null);
|
|
try testing.expectEqual(@as(u8, 1), retry_info.?.retry_count);
|
|
try testing.expect(retry_info.?.can_retry); // Can retry eventually (not exhausted)
|
|
|
|
// Stats should show retry
|
|
const stats = manager.getStats();
|
|
try testing.expectEqual(@as(u32, 1), stats.retrying_pieces);
|
|
try testing.expectEqual(@as(u32, 0), stats.permanently_failed);
|
|
|
|
// Piece cannot be requested immediately - backoff delay applies
|
|
// canRequestPiece checks both shouldRetry AND canRetryNow (which has a delay)
|
|
try testing.expect(!manager.canRequestPiece(0)); // Backoff period not elapsed
|
|
}
|
|
|
|
test "download manager max retries exceeded" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const peer_id = "test_peer";
|
|
const available_pieces = [_]u32{ 0 };
|
|
try manager.addPeer(peer_id, &available_pieces);
|
|
|
|
// Request and fail piece MAX_RETRIES times
|
|
var i: u8 = 0;
|
|
while (i < PieceRetryTracker.MAX_RETRIES) : (i += 1) {
|
|
try manager.requestPiece(0, .high, peer_id);
|
|
try manager.processRequests(1);
|
|
try manager.handleDownloadFailure(0, "Network error");
|
|
}
|
|
|
|
// After max retries, piece should not be requestable (shouldRetry returns false)
|
|
try testing.expect(!manager.canRequestPiece(0));
|
|
|
|
// Stats should show permanent failure
|
|
const stats = manager.getStats();
|
|
try testing.expectEqual(@as(u32, 0), stats.retrying_pieces);
|
|
try testing.expectEqual(@as(u32, 1), stats.permanently_failed);
|
|
|
|
// Check retry info
|
|
const retry_info = manager.getPieceRetryInfo(0);
|
|
try testing.expect(retry_info != null);
|
|
try testing.expect(!retry_info.?.can_retry);
|
|
}
|
|
|
|
test "download manager successful download clears retry tracker" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const test_file = "test_retry_clear.bin";
|
|
try manager.setOutputFile(test_file);
|
|
|
|
const peer_id = "test_peer";
|
|
const available_pieces = [_]u32{ 0 };
|
|
try manager.addPeer(peer_id, &available_pieces);
|
|
|
|
// Request piece
|
|
try manager.requestPiece(0, .high, peer_id);
|
|
try manager.processRequests(1);
|
|
|
|
// Fail once
|
|
try manager.handleDownloadFailure(0, "Temporary error");
|
|
try testing.expect(manager.getPieceRetryInfo(0) != null);
|
|
|
|
// Now succeed
|
|
const test_data = "Test piece data";
|
|
const piece_hash = try HashUtils.sha256(test_data);
|
|
try manager.handlePieceData(0, test_data, piece_hash);
|
|
|
|
// Retry tracker should be cleared
|
|
try testing.expect(manager.getPieceRetryInfo(0) == null);
|
|
|
|
// Stats should show no retries or failures
|
|
const stats = manager.getStats();
|
|
try testing.expectEqual(@as(u32, 0), stats.retrying_pieces);
|
|
try testing.expectEqual(@as(u32, 0), stats.permanently_failed);
|
|
|
|
// Clean up
|
|
std.fs.cwd().deleteFile(test_file) catch |err| {
|
|
std.log.warn("Failed to cleanup test file {s}: {}", .{ test_file, err });
|
|
};
|
|
}
|
|
|
|
test "peer selection avoids failed peer" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Create test peers - all must be added before selectPeerForPiece works
|
|
const peers = [_][]const u8{ "peer1", "peer2", "peer3" };
|
|
const available_pieces = [_]u32{ 0, 1, 2 };
|
|
|
|
// Add all peers with piece 0 available
|
|
for (peers) |peer| {
|
|
try manager.addPeer(peer, &available_pieces);
|
|
}
|
|
|
|
// Select peer for first attempt (no history)
|
|
const first_peer = manager.selectPeerForPiece(0, &peers);
|
|
try testing.expect(first_peer != null);
|
|
|
|
// Simulate failure with peer1
|
|
try manager.requestPiece(0, .high, "peer1");
|
|
try manager.processRequests(1);
|
|
try manager.handleDownloadFailure(0, "Failed");
|
|
|
|
// Now select peer - should prefer different peer
|
|
const second_peer = manager.selectPeerForPiece(0, &peers);
|
|
try testing.expect(second_peer != null);
|
|
|
|
// If there are alternative peers, it should pick a different one
|
|
if (peers.len > 1) {
|
|
// Note: We can't guarantee which peer is selected, but we can verify
|
|
// that selectPeerForPiece returns a valid peer
|
|
var found = false;
|
|
for (peers) |p| {
|
|
if (mem.eql(u8, p, second_peer.?)) {
|
|
found = true;
|
|
break;
|
|
}
|
|
}
|
|
try testing.expect(found);
|
|
}
|
|
}
|
|
|
|
test "exponential backoff timing" {
|
|
var tracker = PieceRetryTracker.init();
|
|
|
|
// No failures - base delay (500ms * 2^0 = 500ms)
|
|
try testing.expectEqual(@as(i64, 500), tracker.getRetryDelay());
|
|
|
|
// First failure - 500ms * 2^1 = 1000ms
|
|
tracker.retry_count = 1;
|
|
try testing.expectEqual(@as(i64, 1000), tracker.getRetryDelay());
|
|
|
|
// Second failure - 500ms * 2^2 = 2000ms
|
|
tracker.retry_count = 2;
|
|
try testing.expectEqual(@as(i64, 2000), tracker.getRetryDelay());
|
|
|
|
// Third failure - 500ms * 2^3 = 4000ms
|
|
tracker.retry_count = 3;
|
|
try testing.expectEqual(@as(i64, 4000), tracker.getRetryDelay());
|
|
}
|
|
|
|
// IMP-M1 FIX: Tests for per-peer piece tracking
|
|
test "PeerPieceMap basic operations" {
|
|
const allocator = testing.allocator;
|
|
var map = PeerPieceMap.init(allocator);
|
|
defer map.deinit();
|
|
|
|
const peer1: [32]u8 = [_]u8{1} ** 32;
|
|
const peer2: [32]u8 = [_]u8{2} ** 32;
|
|
|
|
// Initially empty
|
|
try testing.expect(!map.peerHasPiece(peer1, 0));
|
|
try testing.expectEqual(@as(usize, 0), map.getPeerCountForPiece(0));
|
|
|
|
// Add peer1 with pieces 0, 1, 2
|
|
try map.addPeerPiece(peer1, 0);
|
|
try map.addPeerPiece(peer1, 1);
|
|
try map.addPeerPiece(peer1, 2);
|
|
|
|
try testing.expect(map.peerHasPiece(peer1, 0));
|
|
try testing.expect(map.peerHasPiece(peer1, 1));
|
|
try testing.expect(map.peerHasPiece(peer1, 2));
|
|
try testing.expect(!map.peerHasPiece(peer1, 3));
|
|
try testing.expectEqual(@as(usize, 3), map.getPieceCountForPeer(peer1));
|
|
|
|
// Add peer2 with pieces 1, 2, 3
|
|
try map.addPeerPiece(peer2, 1);
|
|
try map.addPeerPiece(peer2, 2);
|
|
try map.addPeerPiece(peer2, 3);
|
|
|
|
// Piece 0 has 1 peer, pieces 1,2 have 2 peers, piece 3 has 1 peer
|
|
try testing.expectEqual(@as(usize, 1), map.getPeerCountForPiece(0));
|
|
try testing.expectEqual(@as(usize, 2), map.getPeerCountForPiece(1));
|
|
try testing.expectEqual(@as(usize, 2), map.getPeerCountForPiece(2));
|
|
try testing.expectEqual(@as(usize, 1), map.getPeerCountForPiece(3));
|
|
|
|
// Remove peer1's piece 1
|
|
map.removePeerPiece(peer1, 1);
|
|
try testing.expect(!map.peerHasPiece(peer1, 1));
|
|
try testing.expectEqual(@as(usize, 1), map.getPeerCountForPiece(1));
|
|
|
|
// Remove peer1 entirely
|
|
map.removePeer(peer1);
|
|
try testing.expect(!map.peerHasPiece(peer1, 0));
|
|
try testing.expect(!map.peerHasPiece(peer1, 2));
|
|
try testing.expectEqual(@as(usize, 0), map.getPeerCountForPiece(0));
|
|
|
|
// peer2 should still have its pieces
|
|
try testing.expect(map.peerHasPiece(peer2, 1));
|
|
try testing.expect(map.peerHasPiece(peer2, 2));
|
|
try testing.expect(map.peerHasPiece(peer2, 3));
|
|
}
|
|
|
|
test "download manager per-peer piece tracking" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Add two peers with overlapping pieces
|
|
const peer1 = "peer1_id_for_testing_1234567";
|
|
const peer2 = "peer2_id_for_testing_7654321";
|
|
|
|
const pieces1 = [_]u32{ 0, 1, 2 };
|
|
const pieces2 = [_]u32{ 1, 2, 3 };
|
|
|
|
try manager.addPeer(peer1, &pieces1);
|
|
try manager.addPeer(peer2, &pieces2);
|
|
|
|
// Verify per-peer tracking
|
|
var peer1_array: [32]u8 = [_]u8{0} ** 32;
|
|
@memcpy(peer1_array[0..peer1.len], peer1);
|
|
var peer2_array: [32]u8 = [_]u8{0} ** 32;
|
|
@memcpy(peer2_array[0..peer2.len], peer2);
|
|
|
|
// peer1 should have pieces 0,1,2
|
|
try testing.expect(manager.peer_piece_map.peerHasPiece(peer1_array, 0));
|
|
try testing.expect(manager.peer_piece_map.peerHasPiece(peer1_array, 1));
|
|
try testing.expect(manager.peer_piece_map.peerHasPiece(peer1_array, 2));
|
|
try testing.expect(!manager.peer_piece_map.peerHasPiece(peer1_array, 3));
|
|
|
|
// peer2 should have pieces 1,2,3
|
|
try testing.expect(!manager.peer_piece_map.peerHasPiece(peer2_array, 0));
|
|
try testing.expect(manager.peer_piece_map.peerHasPiece(peer2_array, 1));
|
|
try testing.expect(manager.peer_piece_map.peerHasPiece(peer2_array, 2));
|
|
try testing.expect(manager.peer_piece_map.peerHasPiece(peer2_array, 3));
|
|
|
|
// Piece availability counts
|
|
try testing.expectEqual(@as(usize, 1), manager.peer_piece_map.getPeerCountForPiece(0));
|
|
try testing.expectEqual(@as(usize, 2), manager.peer_piece_map.getPeerCountForPiece(1));
|
|
try testing.expectEqual(@as(usize, 2), manager.peer_piece_map.getPeerCountForPiece(2));
|
|
try testing.expectEqual(@as(usize, 1), manager.peer_piece_map.getPeerCountForPiece(3));
|
|
|
|
// Update availability - peer1 no longer has piece 1
|
|
try manager.updatePeerAvailability(peer1, 1, false);
|
|
try testing.expect(!manager.peer_piece_map.peerHasPiece(peer1_array, 1));
|
|
try testing.expectEqual(@as(usize, 1), manager.peer_piece_map.getPeerCountForPiece(1));
|
|
|
|
// Remove peer2
|
|
manager.removePeer(peer2);
|
|
try testing.expect(!manager.peer_piece_map.peerHasPiece(peer2_array, 1));
|
|
try testing.expect(!manager.peer_piece_map.peerHasPiece(peer2_array, 2));
|
|
try testing.expect(!manager.peer_piece_map.peerHasPiece(peer2_array, 3));
|
|
}
|
|
|
|
test "selectPeerForPiece uses per-peer tracking" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
// peer1 has piece 0, peer2 has piece 1
|
|
const peer1 = "peer1_has_piece_0___________";
|
|
const peer2 = "peer2_has_piece_1___________";
|
|
|
|
const pieces1 = [_]u32{0};
|
|
const pieces2 = [_]u32{1};
|
|
|
|
try manager.addPeer(peer1, &pieces1);
|
|
try manager.addPeer(peer2, &pieces2);
|
|
|
|
const peers = [_][]const u8{ peer1, peer2 };
|
|
|
|
// For piece 0, should select peer1 (who has it)
|
|
const selected_for_0 = manager.selectPeerForPiece(0, &peers);
|
|
try testing.expect(selected_for_0 != null);
|
|
try testing.expectEqualStrings(peer1, selected_for_0.?);
|
|
|
|
// For piece 1, should select peer2 (who has it)
|
|
const selected_for_1 = manager.selectPeerForPiece(1, &peers);
|
|
try testing.expect(selected_for_1 != null);
|
|
try testing.expectEqualStrings(peer2, selected_for_1.?);
|
|
|
|
// For piece 2 (no one has it), should return null (no fallback)
|
|
// NO FALLBACK FIX: Don't send requests to peers who aren't known to have the piece
|
|
const selected_for_2 = manager.selectPeerForPiece(2, &peers);
|
|
try testing.expect(selected_for_2 == null);
|
|
}
|
|
|
|
// ============================================================================
|
|
// Additional coverage tests for uncovered code paths
|
|
// ============================================================================
|
|
|
|
test "DownloadState getTimeRemaining" {
|
|
var state = DownloadState.init(1000, 10);
|
|
|
|
// Initially no progress - should return -1 (unknown)
|
|
const time_initial = state.getTimeRemaining();
|
|
try testing.expect(time_initial == -1 or time_initial >= 0);
|
|
|
|
// Complete download - should return 0
|
|
state.downloaded_bytes.store(1000, .release);
|
|
const time_complete = state.getTimeRemaining();
|
|
try testing.expectEqual(@as(i64, 0), time_complete);
|
|
}
|
|
|
|
test "DownloadState markPieceFailed" {
|
|
var state = DownloadState.init(1000, 10);
|
|
|
|
try testing.expectEqual(@as(u32, 0), state.failed_pieces.load(.acquire));
|
|
|
|
state.markPieceFailed();
|
|
try testing.expectEqual(@as(u32, 1), state.failed_pieces.load(.acquire));
|
|
|
|
state.markPieceFailed();
|
|
try testing.expectEqual(@as(u32, 2), state.failed_pieces.load(.acquire));
|
|
}
|
|
|
|
test "DownloadState getCompletionStats" {
|
|
var state = DownloadState.init(1000, 10);
|
|
|
|
state.markPieceCompleted();
|
|
state.markPieceCompleted();
|
|
state.markPieceFailed();
|
|
|
|
const stats = state.getCompletionStats();
|
|
try testing.expectEqual(@as(u32, 2), stats.completed);
|
|
try testing.expectEqual(@as(u32, 1), stats.failed);
|
|
try testing.expectEqual(@as(u32, 10), stats.total);
|
|
}
|
|
|
|
test "DownloadRequest getPeerId" {
|
|
const request = DownloadRequest.create(0, 0, 1024, .normal, "test_peer_id") orelse return;
|
|
const peer_id = request.getPeerId();
|
|
try testing.expect(peer_id.len == 32);
|
|
try testing.expect(std.mem.startsWith(u8, peer_id, "test_peer_id"));
|
|
}
|
|
|
|
test "DownloadRequest create with overflow" {
|
|
// Test offset + length overflow protection
|
|
const result = DownloadRequest.create(0, std.math.maxInt(u64), 1024, .normal, "peer");
|
|
try testing.expect(result == null); // Should fail due to overflow
|
|
}
|
|
|
|
test "PeerRequestTracker basic operations" {
|
|
const allocator = testing.allocator;
|
|
var tracker = PeerRequestTracker.init(allocator, 10, 1024);
|
|
defer tracker.deinit();
|
|
|
|
const peer_id: [32]u8 = [_]u8{1} ** 32;
|
|
|
|
// Initially can request
|
|
try testing.expect(tracker.canRequestFromPeer(peer_id));
|
|
try testing.expect(tracker.getAvailableSlots(peer_id) > 0);
|
|
|
|
// Record a request
|
|
try tracker.recordRequest(peer_id, 0);
|
|
try testing.expect(tracker.isPieceInFlight(peer_id, 0));
|
|
try testing.expect(tracker.isPieceInFlightToAny(0));
|
|
|
|
// Complete the request
|
|
tracker.recordCompletion(peer_id, 0);
|
|
try testing.expect(!tracker.isPieceInFlight(peer_id, 0));
|
|
try testing.expect(!tracker.isPieceInFlightToAny(0));
|
|
}
|
|
|
|
test "PeerRequestTracker recordCompletionWithSize" {
|
|
const allocator = testing.allocator;
|
|
var tracker = PeerRequestTracker.init(allocator, 10, 1024);
|
|
defer tracker.deinit();
|
|
|
|
const peer_id: [32]u8 = [_]u8{2} ** 32;
|
|
|
|
try tracker.recordRequest(peer_id, 5);
|
|
tracker.recordCompletionWithSize(peer_id, 5, 2048, true);
|
|
try testing.expect(!tracker.isPieceInFlight(peer_id, 5));
|
|
}
|
|
|
|
test "PeerRequestTracker removePeer" {
|
|
const allocator = testing.allocator;
|
|
var tracker = PeerRequestTracker.init(allocator, 10, 1024);
|
|
defer tracker.deinit();
|
|
|
|
const peer_id: [32]u8 = [_]u8{3} ** 32;
|
|
|
|
try tracker.recordRequest(peer_id, 0);
|
|
try tracker.recordRequest(peer_id, 1);
|
|
|
|
tracker.removePeer(peer_id);
|
|
try testing.expect(!tracker.isPieceInFlight(peer_id, 0));
|
|
try testing.expect(!tracker.isPieceInFlight(peer_id, 1));
|
|
}
|
|
|
|
test "PeerRequestTracker getTotalInFlight" {
|
|
const allocator = testing.allocator;
|
|
var tracker = PeerRequestTracker.init(allocator, 10, 1024);
|
|
defer tracker.deinit();
|
|
|
|
const peer1: [32]u8 = [_]u8{1} ** 32;
|
|
const peer2: [32]u8 = [_]u8{2} ** 32;
|
|
|
|
try tracker.recordRequest(peer1, 0);
|
|
try tracker.recordRequest(peer2, 1);
|
|
|
|
const total = tracker.getTotalInFlight();
|
|
try testing.expectEqual(@as(u32, 2), total);
|
|
}
|
|
|
|
test "PeerRequestTracker getMetricsStats" {
|
|
const allocator = testing.allocator;
|
|
var tracker = PeerRequestTracker.init(allocator, 10, 1024);
|
|
defer tracker.deinit();
|
|
|
|
const stats = tracker.getMetricsStats();
|
|
try testing.expect(stats.peer_count >= 0);
|
|
}
|
|
|
|
test "DownloadManager endgame mode" {
|
|
const allocator = testing.allocator;
|
|
// Create manager with 20 pieces so we can mark 19 complete (95%) to trigger endgame
|
|
var manager = try DownloadManager.init(200, 20, .rarest_first, 10, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Initially not in endgame
|
|
try testing.expect(!manager.isInEndgame());
|
|
|
|
// Add peers with pieces
|
|
const peer1 = "peer1_endgame_test_123456789";
|
|
const pieces = [_]u32{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
|
|
try manager.addPeer(peer1, &pieces);
|
|
|
|
// Mark 19 out of 20 pieces as complete (95%) to trigger endgame (threshold is 0.95)
|
|
var i: u32 = 0;
|
|
while (i < 19) : (i += 1) {
|
|
manager.state.markPieceCompleted();
|
|
// Mark piece as downloaded in selector
|
|
if (manager.selector.availability_map.getPtr(i)) |piece_info| {
|
|
piece_info.is_downloaded = true;
|
|
piece_info.is_verified = true;
|
|
}
|
|
}
|
|
|
|
// Check endgame mode - should now be active at 95% completion
|
|
manager.checkEndgameMode();
|
|
try testing.expect(manager.isInEndgame());
|
|
}
|
|
|
|
test "DownloadManager needsEndgameBroadcast" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(100, 10, .rarest_first, 10, allocator);
|
|
defer manager.deinit();
|
|
|
|
// Initially no broadcast needed
|
|
try testing.expect(!manager.needsEndgameBroadcast());
|
|
|
|
// Activate endgame manually
|
|
manager.endgame_active = true;
|
|
manager.endgame_broadcast_pending = true;
|
|
|
|
// Should return true and clear the flag
|
|
try testing.expect(manager.needsEndgameBroadcast());
|
|
try testing.expect(!manager.needsEndgameBroadcast()); // Second call should return false
|
|
}
|
|
|
|
test "DownloadManager getRemainingPieceCount" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(100, 10, .rarest_first, 10, allocator);
|
|
defer manager.deinit();
|
|
|
|
try testing.expectEqual(@as(u32, 10), manager.getRemainingPieceCount());
|
|
|
|
manager.state.markPieceCompleted();
|
|
manager.state.markPieceCompleted();
|
|
|
|
try testing.expectEqual(@as(u32, 8), manager.getRemainingPieceCount());
|
|
}
|
|
|
|
test "DownloadManager isComplete" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(100, 2, .rarest_first, 50, allocator);
|
|
defer manager.deinit();
|
|
|
|
try testing.expect(!manager.isComplete());
|
|
|
|
manager.state.markPieceCompleted();
|
|
try testing.expect(!manager.isComplete());
|
|
|
|
manager.state.markPieceCompleted();
|
|
try testing.expect(manager.isComplete());
|
|
}
|
|
|
|
test "DownloadManager setPiecePriority" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const peer_id = "test_peer";
|
|
const available_pieces = [_]u32{0};
|
|
try manager.addPeer(peer_id, &available_pieces);
|
|
|
|
try manager.setPiecePriority(0, .high);
|
|
// Verify piece priority was set (indirectly through selection order)
|
|
const needed = try manager.getNeededPieces(1);
|
|
defer manager.allocator.free(needed);
|
|
try testing.expect(needed.len > 0);
|
|
}
|
|
|
|
test "DownloadManager selectLeastLoadedPeer" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const peer1 = "peer1_least_loaded_test_1234";
|
|
const peer2 = "peer2_least_loaded_test_5678";
|
|
const pieces = [_]u32{0};
|
|
|
|
try manager.addPeer(peer1, &pieces);
|
|
try manager.addPeer(peer2, &pieces);
|
|
|
|
// Both peers have piece 0 - should select one
|
|
const selected = manager.selectLeastLoadedPeer(0);
|
|
try testing.expect(selected != null);
|
|
}
|
|
|
|
test "DownloadManager reassignPiece" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const peer1 = "peer1_reassign_test_12345678";
|
|
const peer2 = "peer2_reassign_test_87654321";
|
|
const pieces = [_]u32{0};
|
|
|
|
try manager.addPeer(peer1, &pieces);
|
|
try manager.addPeer(peer2, &pieces);
|
|
|
|
// Request piece from peer1
|
|
try manager.requestPiece(0, .normal, peer1);
|
|
|
|
// Reassign to peer2
|
|
var peer2_array: [32]u8 = [_]u8{0} ** 32;
|
|
@memcpy(peer2_array[0..peer2.len], peer2);
|
|
|
|
const reassigned = manager.reassignPiece(0, peer2_array);
|
|
try testing.expect(reassigned);
|
|
|
|
// Try to reassign non-existent piece
|
|
const not_found = manager.reassignPiece(99, peer2_array);
|
|
try testing.expect(!not_found);
|
|
}
|
|
|
|
test "DownloadManager getPeerLoads" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const peer1 = "peer1_loads_test_123456789ab";
|
|
const pieces = [_]u32{ 0, 1, 2 };
|
|
try manager.addPeer(peer1, &pieces);
|
|
|
|
// Add some requests
|
|
try manager.requestPiece(0, .normal, peer1);
|
|
try manager.requestPiece(1, .normal, peer1);
|
|
|
|
var loads = try manager.getPeerLoads(allocator);
|
|
defer loads.deinit();
|
|
|
|
try testing.expect(loads.count() > 0);
|
|
}
|
|
|
|
test "DownloadManager getPendingCountForPeer" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const peer1 = "peer1_pending_count_test_123";
|
|
const pieces = [_]u32{ 0, 1, 2 };
|
|
try manager.addPeer(peer1, &pieces);
|
|
|
|
var peer1_array: [32]u8 = [_]u8{0} ** 32;
|
|
@memcpy(peer1_array[0..peer1.len], peer1);
|
|
|
|
// Initially zero
|
|
try testing.expectEqual(@as(usize, 0), manager.getPendingCountForPeer(peer1_array));
|
|
|
|
// Add request
|
|
try manager.requestPiece(0, .normal, peer1);
|
|
try testing.expectEqual(@as(usize, 1), manager.getPendingCountForPeer(peer1_array));
|
|
}
|
|
|
|
test "DownloadManager getIncompletePieces" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(300, 3, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const peer1 = "peer1_incomplete_test_123456";
|
|
const pieces = [_]u32{ 0, 1, 2 };
|
|
try manager.addPeer(peer1, &pieces);
|
|
|
|
// All pieces should be incomplete initially
|
|
const incomplete = try manager.getIncompletePieces();
|
|
defer allocator.free(incomplete);
|
|
try testing.expectEqual(@as(usize, 3), incomplete.len);
|
|
}
|
|
|
|
test "DownloadManager getPeersWithPiece" {
|
|
const allocator = testing.allocator;
|
|
var manager = try DownloadManager.init(1000, 10, .rarest_first, 100, allocator);
|
|
defer manager.deinit();
|
|
|
|
const peer1 = "peer1_get_peers_test_1234567";
|
|
const peer2 = "peer2_get_peers_test_7654321";
|
|
const pieces = [_]u32{0};
|
|
|
|
try manager.addPeer(peer1, &pieces);
|
|
try manager.addPeer(peer2, &pieces);
|
|
|
|
var buffer: [128]u8 = undefined;
|
|
const count = manager.getPeersWithPiece(0, &buffer);
|
|
try testing.expectEqual(@as(usize, 2), count);
|
|
}
|
|
|
|
test "DownloadQueue operations" {
|
|
const allocator = testing.allocator;
|
|
var queue = DownloadQueue.init(allocator);
|
|
defer queue.deinit();
|
|
|
|
// Add downloads - returns pointer to DownloadManager
|
|
const dm1 = try queue.addDownload(1000, 10, .rarest_first, 100);
|
|
const dm2 = try queue.addDownload(2000, 20, .sequential, 100);
|
|
|
|
// Pointers should be different
|
|
try testing.expect(dm1 != dm2);
|
|
|
|
// Check queue size
|
|
try testing.expectEqual(@as(usize, 2), queue.downloads.items.len);
|
|
|
|
// Check completion (not complete yet)
|
|
try testing.expect(!queue.areAllComplete());
|
|
}
|
|
|
|
test "PieceRetryTracker basic operations" {
|
|
var tracker = PieceRetryTracker.init();
|
|
|
|
// Initial state
|
|
try testing.expectEqual(@as(u8, 0), tracker.retry_count);
|
|
try testing.expect(tracker.last_peer == null);
|
|
|
|
// Record failure increments count
|
|
tracker.recordFailure("Failed");
|
|
try testing.expectEqual(@as(u8, 1), tracker.retry_count);
|
|
|
|
// Reset clears tracking
|
|
tracker.reset();
|
|
try testing.expectEqual(@as(u8, 0), tracker.retry_count);
|
|
} |