This commit is contained in:
2026-02-06 21:03:59 -03:00
commit 2b7ab5f570
267 changed files with 176026 additions and 0 deletions

341
src/files/README.md Normal file
View File

@@ -0,0 +1,341 @@
# File Sharing Module
A comprehensive BitTorrent-inspired file sharing system implemented in Zig for the P2P library.
## Overview
This module provides a complete file sharing and transfer system with the following features:
- **File chunking and metadata management**
- **Piece selection algorithms** (rarest-first, random, sequential, priority-based)
- **Download management** with progress tracking and rate limiting
- **Upload management** with bandwidth control and peer coordination
- **Transfer protocol** for peer-to-peer communication
- **Hash-based integrity verification** using SHA-256
- **Comprehensive testing** suite
## Architecture
### Core Components
1. **Hash Module** (`hash.zig`)
- SHA-256 hashing for piece verification
- Content addressing and metadata hashing
- Batch verification operations
- Hash pool for efficient computation
2. **File Module** (`file.zig`)
- File metadata creation and management
- File chunking into pieces (fixed and variable size)
- File reading/writing operations with streaming support
- Integrity verification with SHA-256
- File type detection and classification
- Compression/decompression utilities
- File backup and copy operations
- Progress tracking for file operations
3. **Piece Selection Module** (`piece.zig`)
- Multiple selection strategies
- Piece availability tracking
- Priority-based selection
- Piece pool management
4. **Download Module** (`download.zig`)
- Download state tracking
- Piece request management
- Progress monitoring
- Download queue coordination
5. **Upload Module** (`upload.zig`)
- Upload state management
- Bandwidth limiting and rate control
- Peer upload coordination
- Upload queue management
6. **Transfer Module** (`transfer.zig`)
- Protocol message handling
- Session management
- Peer communication
- Error handling and recovery
7. **Manager Module** (`manager.zig`)
- Central coordination
- Session lifecycle management
- Configuration and statistics
- Integration point for the entire system
## Key Features
### Piece Selection Strategies
- **Rarest First**: Prioritizes pieces that are less available
- **Random**: Random piece selection
- **Sequential**: Sequential piece selection
- **Priority First**: Priority-based selection
- **Balanced**: Combination of rarity and priority
### Download Management
- Concurrent download tracking
- Progress monitoring with speed calculation
- Time remaining estimation
- Bandwidth utilization tracking
- Piece verification during download
### Upload Management
- Bandwidth limiting and throttling
- Peer upload coordination
- Upload queue management
- Rate limiting per peer
- Bandwidth utilization monitoring
### File Integrity
- SHA-256 hash verification for each piece
- Content-based addressing
- Batch verification operations
- Corruption detection and recovery
### Transfer Protocol
- Message-based communication
- Session management
- Error handling and recovery
- Timeout management
- Peer capability exchange
## Usage Examples
### Basic File Operations
```zig
const allocator = std.heap.page_allocator;
// File metadata creation
const chunker = FileChunker.init(DEFAULT_PIECE_SIZE, allocator);
const metadata = try chunker.createMetadata("path/to/file.bin");
defer allocator.free(metadata.piece_hashes);
// File integrity verification
const is_valid = try chunker.verifyFile("path/to/file.bin", metadata);
// Streaming file reader
var reader = try FileReader.init("large_file.bin", allocator, 64 * 1024);
defer reader.deinit();
try reader.readInChunks(fn(data: []const u8) Error!void {
// Process chunk data
std.debug.print("Read {} bytes\n", .{data.len});
});
// File operations with progress
try FileUtils.copyFileWithProgress(
"source.bin",
"dest.bin",
allocator,
fn(current: u64, total: u64) void {
const percentage = @as(f64, @floatFromInt(current)) / @as(f64, @floatFromInt(total)) * 100.0;
std.debug.print("Progress: {d:.1}%\n", .{percentage});
}
);
// File type detection and compression
const file_type = FileUtils.getFileType("document.txt");
const compression_ratio = FileUtils.estimateCompressionRatio("document.txt");
std.debug.print("File type: {s}, estimated ratio: {d:.2}\n", .{
file_type.description(),
compression_ratio
});
```
### Basic File Sharing
```zig
const allocator = std.heap.page_allocator;
const config = FileSharingConfig.default();
var manager = try FileSharingManager.init(config, allocator);
defer manager.deinit();
// Add file for sharing
const session = try manager.addFile("path/to/file.bin");
try manager.startSharing(session.session_id);
// Process sessions
try manager.processSessions();
// Monitor progress
const stats = manager.getStats();
std.debug.print("Progress: {d:.1}%\n", .{stats.getCompletionRate()});
```
### Download Management
```zig
// Configure download settings
const download_config = DownloadConfig{
.max_concurrent_downloads = 4,
.piece_size = 16 * 1024 * 1024, // 16MB
};
// Create download manager
var download_manager = try DownloadManager.init(
file_size,
piece_count,
.rarest_first,
piece_size,
allocator
);
// Set output file
try download_manager.setOutputFile("output.bin");
// Add peer and request pieces
try download_manager.addPeer("peer_id", &available_pieces);
try download_manager.requestPiece(0, .high, "peer_id");
// Process downloads
try download_manager.processRequests(4);
```
### Upload Management
```zig
// Configure upload settings
var upload_manager = try UploadManager.init(
1024 * 1024, // 1MB/s max bandwidth
piece_size,
allocator
);
// Add available pieces
for (piece_hashes) |hash, i| {
try upload_manager.addAvailablePiece(@as(u32, @intCast(i)), hash);
}
// Handle upload requests
const accepted = try upload_manager.handleUploadRequest(
piece_index,
offset,
length,
"peer_id",
.normal
);
// Process uploads
try upload_manager.processRequests(4);
```
### Piece Selection
```zig
// Create piece selector
var selector = PieceSelector.init(.rarest_first, seed, allocator);
defer selector.deinit();
// Add pieces with availability
for (available_pieces) |piece_index| {
try selector.addPiece(piece_index, peer_count);
}
// Select next pieces to download
const selected = try selector.selectNext(5);
defer allocator.free(selected);
// Update piece status
try selector.markDownloaded(selected[0]);
try selector.markVerified(selected[0]);
```
## Configuration
### File Sharing Config
```zig
const config = FileSharingConfig{
.piece_size = 16 * 1024 * 1024, // 16MB pieces
.max_concurrent_downloads = 4, // 4 concurrent downloads
.max_concurrent_uploads = 4, // 4 concurrent uploads
.max_bandwidth_download = 1024 * 1024, // 1MB/s download
.max_bandwidth_upload = 1024 * 1024, // 1MB/s upload
.selection_strategy = .rarest_first, // Selection algorithm
.enable_upload = true, // Enable uploading
.enable_download = true, // Enable downloading
.auto_verify = true, // Auto-verify pieces
.temp_dir = "temp", // Temporary directory
};
```
### Performance Configurations
```zig
// High performance configuration
const hp_config = FileSharingConfig.high_performance();
// - 8 concurrent operations
// - 10MB/s bandwidth
// - 32MB pieces
// - Balanced selection
// Low bandwidth configuration
const lb_config = FileSharingConfig.low_bandwidth();
// - 2 concurrent operations
// - 256KB/s bandwidth
// - 8MB pieces
// - Sequential selection
```
## Testing
The module includes comprehensive tests:
- **Unit tests** for each component
- **Integration tests** for end-to-end functionality
- **Performance tests** for large file handling
- **Stress tests** for multiple file operations
- **Error recovery tests** for corrupted data
- **Concurrent access tests** for multi-peer scenarios
Run tests with:
```bash
zig test test/files/test_main.zig
```
## Performance Characteristics
- **Piece Selection**: O(n log n) for sorting-based strategies
- **Hash Verification**: O(n) for batch operations
- **File Chunking**: O(n) where n is file size
- **Memory Usage**: Configurable based on piece size and concurrency
- **Bandwidth Efficiency**: Adaptive rate limiting
## Error Handling
The module includes comprehensive error handling:
- **Network errors**: Connection timeouts, peer disconnections
- **File errors**: Read/write failures, disk space issues
- **Protocol errors**: Message format errors, version mismatches
- **Integrity errors**: Hash mismatches, corrupted pieces
- **Resource errors**: Memory exhaustion, bandwidth limits
## Future Enhancements
Potential improvements for future versions:
- **Encryption**: End-to-end encryption for transfers
- **Compression**: On-the-fly data compression
- **Streaming**: Support for streaming large files
- **DHT**: Distributed hash table integration
- **Magnet Links**: Magnet link support
- **WebRTC**: WebRTC transport for browser compatibility
## Dependencies
- Zig standard library
- No external dependencies for core functionality
- Optional dependencies for enhanced features (compression, encryption)
## License
This module is part of the P2P library and follows the same licensing terms.

View File

@@ -0,0 +1,316 @@
//! Global adaptive concurrency controller using AIMD
//!
//! Dynamically adjusts max_concurrent_downloads based on network health
//! to prevent throughput death spiral while maximizing throughput.
//!
//! Problem: With static high concurrency (e.g., 256) and limited upload bandwidth,
//! requests can starve and timeout, causing retry loops and death spirals.
//!
//! Solution: AIMD (Additive Increase, Multiplicative Decrease) adjusts concurrency
//! based on success/timeout rates, similar to TCP congestion control.
const std = @import("std");
pub const AdaptiveConcurrencyController = struct {
// Configuration (set at init, immutable)
min_concurrency: usize,
max_concurrency: usize,
target_success_rate: f64,
adjustment_cooldown_ns: i128,
// Dynamic state
current_concurrency: usize,
success_rate: f64,
timeout_rate: f64,
// AIMD tracking
consecutive_healthy_cycles: u32,
consecutive_unhealthy_cycles: u32,
cycles_since_increase: u32,
last_adjustment_ns: i128,
// Statistics for current cycle
cycle_successes: u64,
cycle_timeouts: u64,
// EWMA smoothing factor (0.25 = new sample has 25% weight, responsive but smooth)
const ALPHA: f64 = 0.25;
// Cycles between additive increase attempts (fast recovery)
const INCREASE_EPOCH: u32 = 2;
// Required consecutive healthy cycles before considering increase
const HEALTHY_THRESHOLD: u32 = 2;
// Consecutive unhealthy cycles that trigger decrease (require sustained issues)
const UNHEALTHY_THRESHOLD: u32 = 3;
// Timeout rate threshold - only decrease if timeout rate exceeds this
// Lower threshold (10%) provides faster response to congestion
const TIMEOUT_THRESHOLD: f64 = 0.10; // 10% timeout rate
pub fn init(config: Config) AdaptiveConcurrencyController {
return .{
.min_concurrency = config.min_concurrency,
.max_concurrency = config.max_concurrency,
.target_success_rate = config.target_success_rate,
.adjustment_cooldown_ns = @as(i128, config.adjustment_cooldown_ms) * 1_000_000,
.current_concurrency = config.initial_concurrency,
.success_rate = 1.0,
.timeout_rate = 0.0,
.consecutive_healthy_cycles = 0,
.consecutive_unhealthy_cycles = 0,
.cycles_since_increase = 0,
.last_adjustment_ns = 0,
.cycle_successes = 0,
.cycle_timeouts = 0,
};
}
pub const Config = struct {
min_concurrency: usize = 64, // Lower floor - allow aggressive throttling
max_concurrency: usize = 256,
initial_concurrency: usize = 128, // Start moderate, let it find equilibrium
target_success_rate: f64 = 0.90, // 90% success is healthy
adjustment_cooldown_ms: i64 = 1000, // 1 second cooldown
};
/// Record a successful piece completion
pub fn recordSuccess(self: *AdaptiveConcurrencyController) void {
self.cycle_successes += 1;
}
/// Record a timeout/failure
pub fn recordTimeout(self: *AdaptiveConcurrencyController) void {
self.cycle_timeouts += 1;
}
/// Called at end of each processing cycle to evaluate health and adjust
pub fn recordCycleEnd(
self: *AdaptiveConcurrencyController,
current_in_flight: usize,
) void {
const now = std.time.nanoTimestamp();
const total = self.cycle_successes + self.cycle_timeouts;
if (total > 0) {
// Update success/timeout rates with EWMA
const cycle_success_rate = @as(f64, @floatFromInt(self.cycle_successes)) /
@as(f64, @floatFromInt(total));
const cycle_timeout_rate = @as(f64, @floatFromInt(self.cycle_timeouts)) /
@as(f64, @floatFromInt(total));
self.success_rate = (1.0 - ALPHA) * self.success_rate + ALPHA * cycle_success_rate;
self.timeout_rate = (1.0 - ALPHA) * self.timeout_rate + ALPHA * cycle_timeout_rate;
}
// Reset cycle counters
self.cycle_successes = 0;
self.cycle_timeouts = 0;
// Evaluate health: healthy if success rate meets target AND timeout rate is below threshold
const is_healthy = self.success_rate >= self.target_success_rate and
self.timeout_rate < TIMEOUT_THRESHOLD;
if (is_healthy) {
self.consecutive_healthy_cycles += 1;
self.consecutive_unhealthy_cycles = 0;
} else {
self.consecutive_unhealthy_cycles += 1;
self.consecutive_healthy_cycles = 0;
}
// Check cooldown period to prevent oscillation
if (now - self.last_adjustment_ns < self.adjustment_cooldown_ns) {
return;
}
// AIMD: Multiplicative decrease on sustained unhealthy periods
if (self.consecutive_unhealthy_cycles >= UNHEALTHY_THRESHOLD) {
self.decreaseConcurrency();
self.last_adjustment_ns = now;
self.consecutive_unhealthy_cycles = 0;
self.cycles_since_increase = 0;
return;
}
// AIMD: Additive increase on sustained healthy periods with high utilization
const utilization = if (self.current_concurrency > 0)
@as(f64, @floatFromInt(current_in_flight)) /
@as(f64, @floatFromInt(self.current_concurrency))
else
0.0;
if (self.consecutive_healthy_cycles >= HEALTHY_THRESHOLD and utilization > 0.8) {
self.cycles_since_increase += 1;
if (self.cycles_since_increase >= INCREASE_EPOCH) {
self.increaseConcurrency();
self.last_adjustment_ns = now;
self.cycles_since_increase = 0;
}
}
}
/// Get current effective concurrency limit
pub fn getEffectiveConcurrency(self: *const AdaptiveConcurrencyController) usize {
return self.current_concurrency;
}
/// AIMD: Additive increase - recover throughput when healthy
/// Uses percentage-based increase: +20% of current, minimum +16
fn increaseConcurrency(self: *AdaptiveConcurrencyController) void {
// Increase by 20% of current, but at least 16 and at most 64
const pct_increase = (self.current_concurrency * 20) / 100;
const increment: usize = @min(64, @max(16, pct_increase));
self.current_concurrency = @min(
self.max_concurrency,
self.current_concurrency + increment,
);
std.log.info("ADAPTIVE: Increased concurrency to {} (+{}) (success={d:.1}%)", .{
self.current_concurrency,
increment,
self.success_rate * 100,
});
}
/// AIMD: Multiplicative decrease on congestion
/// Uses 20% reduction (x0.80) - aggressive enough to escape death spiral
fn decreaseConcurrency(self: *AdaptiveConcurrencyController) void {
// Reduce by 20% (multiply by 0.80)
const reduction = (self.current_concurrency * 20) / 100;
const new_concurrency = if (self.current_concurrency > reduction)
self.current_concurrency - reduction
else
self.min_concurrency;
self.current_concurrency = @max(self.min_concurrency, new_concurrency);
std.log.warn("ADAPTIVE: Decreased concurrency to {} (success={d:.1}%, timeout={d:.1}%)", .{
self.current_concurrency,
self.success_rate * 100,
self.timeout_rate * 100,
});
}
/// Get diagnostic statistics
pub fn getStats(self: *const AdaptiveConcurrencyController) Stats {
return .{
.current_concurrency = self.current_concurrency,
.success_rate = self.success_rate,
.timeout_rate = self.timeout_rate,
.consecutive_healthy = self.consecutive_healthy_cycles,
.consecutive_unhealthy = self.consecutive_unhealthy_cycles,
};
}
pub const Stats = struct {
current_concurrency: usize,
success_rate: f64,
timeout_rate: f64,
consecutive_healthy: u32,
consecutive_unhealthy: u32,
};
};
// Tests
test "AdaptiveConcurrencyController basic initialization" {
const controller = AdaptiveConcurrencyController.init(.{
.initial_concurrency = 200,
.min_concurrency = 64,
.max_concurrency = 256,
});
try std.testing.expectEqual(@as(usize, 200), controller.current_concurrency);
try std.testing.expectEqual(@as(usize, 64), controller.min_concurrency);
try std.testing.expectEqual(@as(usize, 256), controller.max_concurrency);
try std.testing.expectEqual(@as(f64, 1.0), controller.success_rate);
try std.testing.expectEqual(@as(f64, 0.0), controller.timeout_rate);
}
test "AdaptiveConcurrencyController healthy cycles" {
var controller = AdaptiveConcurrencyController.init(.{
.initial_concurrency = 64,
.adjustment_cooldown_ms = 0, // Disable cooldown for test
});
// Simulate healthy cycles with all successes
for (0..10) |_| {
controller.recordSuccess();
}
controller.recordCycleEnd(60); // 93% utilization
try std.testing.expect(controller.success_rate > 0.9);
try std.testing.expect(controller.consecutive_healthy_cycles >= 1);
}
test "AdaptiveConcurrencyController multiplicative decrease" {
var controller = AdaptiveConcurrencyController.init(.{
.initial_concurrency = 100,
.adjustment_cooldown_ms = 0, // Disable cooldown for test
});
// Simulate unhealthy cycles with high timeout rate (>10%)
// Need 4 consecutive unhealthy cycles to trigger decrease
for (0..6) |_| {
for (0..4) |_| controller.recordSuccess();
for (0..6) |_| controller.recordTimeout(); // 60% timeout rate
controller.recordCycleEnd(100);
}
// Should have decreased (40% success rate is below 90% target, 60% timeout > 10%)
try std.testing.expect(controller.current_concurrency < 100);
}
test "AdaptiveConcurrencyController respects minimum" {
var controller = AdaptiveConcurrencyController.init(.{
.initial_concurrency = 100,
.min_concurrency = 64,
.adjustment_cooldown_ms = 0,
});
// Force many decreases with very high timeout rate
for (0..30) |_| {
for (0..1) |_| controller.recordSuccess();
for (0..9) |_| controller.recordTimeout();
controller.recordCycleEnd(100);
}
// Should not go below minimum
try std.testing.expect(controller.current_concurrency >= 64);
}
test "AdaptiveConcurrencyController respects maximum" {
var controller = AdaptiveConcurrencyController.init(.{
.initial_concurrency = 250,
.max_concurrency = 256,
.adjustment_cooldown_ms = 0,
});
// Simulate many healthy cycles with high utilization to trigger increases
for (0..50) |_| {
for (0..10) |_| controller.recordSuccess();
controller.recordCycleEnd(245); // >95% utilization
}
// Should not exceed maximum
try std.testing.expect(controller.current_concurrency <= 256);
}
test "AdaptiveConcurrencyController getEffectiveConcurrency" {
const controller = AdaptiveConcurrencyController.init(.{
.initial_concurrency = 100,
});
try std.testing.expectEqual(@as(usize, 100), controller.getEffectiveConcurrency());
}
test "AdaptiveConcurrencyController getStats" {
var controller = AdaptiveConcurrencyController.init(.{
.initial_concurrency = 64,
});
// Record some activity
controller.recordSuccess();
controller.recordSuccess();
controller.recordTimeout();
controller.recordCycleEnd(50);
const stats = controller.getStats();
try std.testing.expectEqual(@as(usize, 64), stats.current_concurrency);
try std.testing.expect(stats.success_rate > 0.0);
try std.testing.expect(stats.timeout_rate >= 0.0);
}

3554
src/files/download.zig Normal file

File diff suppressed because it is too large Load Diff

1733
src/files/file.zig Normal file

File diff suppressed because it is too large Load Diff

436
src/files/filesystem.zig Normal file
View File

@@ -0,0 +1,436 @@
//! Filesystem Abstraction Layer
//!
//! Provides a unified interface for filesystem operations that can be backed by
//! either the real filesystem (std.fs) or an in-memory mock filesystem for testing.
//!
//! Usage:
//! ```zig
//! const FS = @import("filesystem.zig").FileSystem;
//!
//! // Opens file using current backend (real or mock)
//! var file = try FS.openFile("/path/to/file", .{});
//! defer file.close();
//!
//! var buf: [1024]u8 = undefined;
//! const n = try file.read(&buf);
//! ```
//!
//! To use MockFS in tests, set `use_mock_fs = true` before importing.
const std = @import("std");
const builtin = @import("builtin");
const Allocator = std.mem.Allocator;
const mock_fs = @import("mock_fs.zig");
/// Compile-time flag to enable mock filesystem
/// Set this in test files before importing filesystem.zig
pub var use_mock_fs: bool = false;
/// Global mock filesystem instance for testing
/// Must be initialized before use when use_mock_fs is true
pub var mock_instance: ?*mock_fs.MockFS = null;
/// File statistics
pub const Stat = struct {
size: u64,
ctime: i128,
mtime: i128,
atime: i128,
};
/// Abstract file handle that wraps either std.fs.File or MockFileHandle
pub const File = struct {
impl: FileImpl,
const FileImpl = union(enum) {
real: std.fs.File,
mock: MockFileState,
};
const MockFileState = struct {
fs: *mock_fs.MockFS,
path: []const u8,
position: u64,
read_only: bool,
};
/// Read data from file at current position
pub fn read(self: *File, buffer: []u8) !usize {
switch (self.impl) {
.real => |f| return f.read(buffer),
.mock => |*state| {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
const content = file.data;
if (state.position >= content.len) {
return 0; // EOF
}
const available = content.len - @as(usize, @intCast(state.position));
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[@intCast(state.position)..][0..to_read]);
state.position += to_read;
return to_read;
},
}
}
/// Read data from file at specific offset (pread)
pub fn preadAll(self: *File, buffer: []u8, offset: u64) !usize {
switch (self.impl) {
.real => |f| return f.preadAll(buffer, offset),
.mock => |state| {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
const content = file.data;
const off: usize = @intCast(@min(offset, content.len));
if (off >= content.len) {
return 0;
}
const available = content.len - off;
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[off..][0..to_read]);
return to_read;
},
}
}
/// Write data to file at current position
pub fn write(self: *File, data: []const u8) !usize {
switch (self.impl) {
.real => |f| return f.write(data),
.mock => |*state| {
if (state.read_only) return error.AccessDenied;
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
// Extend file if necessary
const end_pos = state.position + data.len;
if (end_pos > file.data.len) {
file.resize(end_pos) catch return error.OutOfMemory;
}
// Copy data
const pos: usize = @intCast(state.position);
@memcpy(file.data[pos..][0..data.len], data);
state.position += data.len;
file.modified_at = std.time.timestamp();
return data.len;
},
}
}
/// Write data at specific offset (pwrite)
pub fn pwriteAll(self: *File, data: []const u8, offset: u64) !void {
switch (self.impl) {
.real => |f| try f.pwriteAll(data, offset),
.mock => |state| {
if (state.read_only) return error.AccessDenied;
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
const off: usize = @intCast(offset);
// Extend file if necessary
if (off + data.len > file.data.len) {
file.resize(off + data.len) catch return error.OutOfMemory;
}
// Copy data
@memcpy(file.data[off..][0..data.len], data);
file.modified_at = std.time.timestamp();
},
}
}
/// Seek to position
pub fn seekTo(self: *File, position: u64) !void {
switch (self.impl) {
.real => |f| try f.seekTo(position),
.mock => |*state| {
state.position = position;
},
}
}
/// Get current position
pub fn getPos(self: *File) !u64 {
switch (self.impl) {
.real => |f| return f.getPos(),
.mock => |state| return state.position,
}
}
/// Get file statistics
pub fn stat(self: *File) !Stat {
switch (self.impl) {
.real => |f| {
const s = try f.stat();
return Stat{
.size = s.size,
.ctime = s.ctime,
.mtime = s.mtime,
.atime = s.atime,
};
},
.mock => |state| {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
return Stat{
.size = file.data.len,
.ctime = file.created_at,
.mtime = file.modified_at,
.atime = file.modified_at,
};
},
}
}
/// Sync file to disk (no-op for mock)
pub fn sync(self: *File) !void {
switch (self.impl) {
.real => |f| try f.sync(),
.mock => {},
}
}
/// Close file handle
pub fn close(self: *File) void {
switch (self.impl) {
.real => |f| f.close(),
.mock => {}, // MockFS doesn't track open handles
}
}
};
/// Filesystem operations
pub const FileSystem = struct {
/// Open an existing file
pub fn openFile(path: []const u8, flags: std.fs.File.OpenFlags) !File {
if (mock_instance) |mfs| {
// Check if file exists in mock
if (!mfs.fileExists(path)) {
return error.FileNotFound;
}
return File{
.impl = .{
.mock = .{
.fs = mfs,
.path = path,
.position = 0,
.read_only = flags.mode == .read_only,
},
},
};
} else {
const f = try std.fs.cwd().openFile(path, flags);
return File{ .impl = .{ .real = f } };
}
}
/// Create a new file or truncate existing
pub fn createFile(path: []const u8, flags: std.fs.File.CreateFlags) !File {
if (mock_instance) |mfs| {
// Create file in mock (or truncate if exists)
mfs.writeFile(path, "") catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.AccessDenied,
};
return File{
.impl = .{
.mock = .{
.fs = mfs,
.path = path,
.position = 0,
.read_only = false, // createFile always allows writing
},
},
};
} else {
const f = try std.fs.cwd().createFile(path, flags);
return File{ .impl = .{ .real = f } };
}
}
/// Check if file exists
pub fn fileExists(path: []const u8) bool {
if (mock_instance) |mfs| {
return mfs.fileExists(path);
} else {
std.fs.cwd().access(path, .{}) catch return false;
return true;
}
}
/// Delete a file
pub fn deleteFile(path: []const u8) !void {
if (mock_instance) |mfs| {
mfs.deleteFile(path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
else => return error.AccessDenied,
};
} else {
try std.fs.cwd().deleteFile(path);
}
}
/// Create directory (and parents)
pub fn makePath(path: []const u8) !void {
if (mock_instance) |mfs| {
mfs.makeDir(path) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.AccessDenied,
};
} else {
try std.fs.cwd().makePath(path);
}
}
/// Rename/move a file
pub fn rename(old_path: []const u8, new_path: []const u8) !void {
if (mock_instance) |mfs| {
mfs.rename(old_path, new_path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
error.OutOfMemory => return error.OutOfMemory,
else => return error.AccessDenied,
};
} else {
try std.fs.cwd().rename(old_path, new_path);
}
}
};
// ============================================================================
// Tests
// ============================================================================
test "FileSystem: real filesystem operations" {
// Test with real filesystem (default)
mock_instance = null;
// Just verify the API compiles and works with real fs
const exists = FileSystem.fileExists("/nonexistent_test_file_12345");
try std.testing.expect(!exists);
}
test "FileSystem: mock filesystem operations" {
const allocator = std.testing.allocator;
// Create and set mock
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
// Create a file
var file = try FileSystem.createFile("/test.txt", .{});
_ = try file.write("Hello, World!");
file.close();
// Read it back
var file2 = try FileSystem.openFile("/test.txt", .{});
defer file2.close();
var buf: [100]u8 = undefined;
const n = try file2.read(&buf);
try std.testing.expectEqualStrings("Hello, World!", buf[0..n]);
}
test "FileSystem: mock pread/pwrite" {
const allocator = std.testing.allocator;
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
// Create file with initial content
try mfs.writeFile("/data.bin", "0123456789");
var file = try FileSystem.openFile("/data.bin", .{ .mode = .read_write });
defer file.close();
// pwrite at offset 5
try file.pwriteAll("XXXXX", 5);
// pread to verify
var buf: [10]u8 = undefined;
const n = try file.preadAll(&buf, 0);
try std.testing.expectEqualStrings("01234XXXXX", buf[0..n]);
}
test "FileSystem: mock stat" {
const allocator = std.testing.allocator;
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
try mfs.writeFile("/stats.txt", "Hello!");
var file = try FileSystem.openFile("/stats.txt", .{});
defer file.close();
const s = try file.stat();
try std.testing.expectEqual(@as(u64, 6), s.size);
}
test "FileSystem: mock file not found" {
const allocator = std.testing.allocator;
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
const result = FileSystem.openFile("/nonexistent.txt", .{});
try std.testing.expectError(error.FileNotFound, result);
}
test "FileSystem: mock directory operations" {
const allocator = std.testing.allocator;
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
try FileSystem.makePath("/foo/bar/baz");
try std.testing.expect(mfs.dirExists("/foo"));
try std.testing.expect(mfs.dirExists("/foo/bar"));
try std.testing.expect(mfs.dirExists("/foo/bar/baz"));
}
test "FileSystem: mock delete and rename" {
const allocator = std.testing.allocator;
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
try mfs.writeFile("/old.txt", "content");
// Rename
try FileSystem.rename("/old.txt", "/new.txt");
try std.testing.expect(!FileSystem.fileExists("/old.txt"));
try std.testing.expect(FileSystem.fileExists("/new.txt"));
// Delete
try FileSystem.deleteFile("/new.txt");
try std.testing.expect(!FileSystem.fileExists("/new.txt"));
}

548
src/files/hash.zig Normal file
View File

@@ -0,0 +1,548 @@
//! Hash functions and integrity verification for file sharing
//!
//! This module provides SHA-256 based hashing for piece verification,
//! content addressing, and integrity checking throughout the file sharing system.
//!
//! Uses Zig's standard library crypto which automatically uses hardware
//! acceleration (SHA-NI on x86_64, SHA2 extensions on ARM64) when available.
const std = @import("std");
const testing = std.testing;
const crypto = std.crypto;
const mem = std.mem;
const fmt = std.fmt;
const core = @import("core");
const Error = core.errors.Error;
/// SHA-256 hash type for piece verification
pub const PieceHash = [32]u8;
/// Content identifier hash (also SHA-256)
pub const ContentHash = [32]u8;
/// Hash utilities and verification functions
pub const HashUtils = struct {
/// Calculate SHA-256 hash of data (uses hardware acceleration when available)
pub fn sha256(data: []const u8) Error!PieceHash {
var hasher = crypto.hash.sha2.Sha256.init(.{});
hasher.update(data);
var hash: PieceHash = undefined;
hasher.final(&hash);
return hash;
}
/// Verify data matches expected hash
pub fn verify(data: []const u8, expected: PieceHash) Error!bool {
const actual = try sha256(data);
return mem.eql(u8, &actual, &expected);
}
/// Create content hash from multiple pieces
pub fn contentHash(pieces: []const PieceHash) Error!ContentHash {
var hasher = crypto.hash.sha2.Sha256.init(.{});
for (pieces) |piece_hash| {
hasher.update(&piece_hash);
}
var hash: ContentHash = undefined;
hasher.final(&hash);
return hash;
}
/// Calculate hash of file metadata
pub fn metadataHash(metadata: FileMetadata) Error!ContentHash {
var hasher = crypto.hash.sha2.Sha256.init(.{});
// Hash file name
hasher.update(metadata.name);
// Hash file size
var size_bytes: [8]u8 = undefined;
@memcpy(&size_bytes, mem.asBytes(&metadata.size));
hasher.update(&size_bytes);
// Hash piece count
var piece_count_bytes: [4]u8 = undefined;
@memcpy(&piece_count_bytes, mem.asBytes(&metadata.piece_count));
hasher.update(&piece_count_bytes);
// Hash piece hashes
for (metadata.piece_hashes) |piece_hash| {
hasher.update(&piece_hash);
}
var hash: ContentHash = undefined;
hasher.final(&hash);
return hash;
}
/// Convert hash to hex string representation
pub fn toHex(hash: PieceHash, allocator: mem.Allocator) Error![]u8 {
return fmt.allocPrint(allocator, "{x}", .{hash});
}
/// Parse hex string to hash
pub fn fromHex(hex_str: []const u8) Error!PieceHash {
if (hex_str.len != 64) {
return Error.InvalidData;
}
var hash: PieceHash = undefined;
for (hex_str, 0..) |c, i| {
const byte_index = i / 2;
const nibble_index = i % 2;
const value = switch (c) {
'0'...'9' => c - '0',
'a'...'f' => c - 'a' + 10,
'A'...'F' => c - 'A' + 10,
else => return Error.InvalidData,
};
if (nibble_index == 0) {
hash[byte_index] = value << 4;
} else {
hash[byte_index] |= value;
}
}
return hash;
}
/// Generate random hash for testing
pub fn random(allocator: mem.Allocator) Error!PieceHash {
const random_bytes = allocator.alloc(u8, 32) catch return Error.OutOfMemory;
defer allocator.free(random_bytes);
crypto.random.bytes(random_bytes);
var hash: PieceHash = undefined;
@memcpy(&hash, random_bytes);
return hash;
}
/// Compare two hashes
pub fn equal(a: PieceHash, b: PieceHash) bool {
return mem.eql(u8, &a, &b);
}
};
/// File metadata structure
pub const FileMetadata = struct {
name: []const u8,
size: u64,
piece_count: u32,
piece_hashes: []const PieceHash,
created_at: i64,
modified_at: i64,
/// Create metadata for a file
/// Note: This allocates a copy of the name. Caller must ensure the returned
/// FileMetadata.name is freed when done, or use FileSharingSession.deinit.
pub fn create(
name: []const u8,
size: u64,
piece_hashes: []const PieceHash,
allocator: mem.Allocator,
) Error!FileMetadata {
// Allocate a copy of the name to ensure it can be freed later
const owned_name = allocator.dupe(u8, name) catch return Error.OutOfMemory;
return FileMetadata{
.name = owned_name,
.size = size,
.piece_count = @as(u32, @intCast(piece_hashes.len)),
.piece_hashes = piece_hashes,
.created_at = std.time.timestamp(),
.modified_at = std.time.timestamp(),
};
}
/// Calculate total size of all pieces
pub fn totalSize(self: FileMetadata) u64 {
return self.size;
}
/// Get piece size (last piece may be smaller)
pub fn pieceSize(self: FileMetadata, piece_index: u32) usize {
const piece_size: u64 = 1 * 1024 * 1024; // 1MB default piece size (must be under 2MB message limit)
// OVERFLOW FIX: Use checked multiplication to prevent overflow
const start = std.math.mul(u64, piece_index, piece_size) catch {
// If overflow occurs, piece_index is invalid - return 0
return 0;
};
if (start + piece_size > self.size) {
return @as(usize, @intCast(self.size - start));
}
return @as(usize, @intCast(piece_size));
}
/// Verify file integrity
pub fn verify(self: FileMetadata, pieces: []const PieceData) Error!bool {
if (pieces.len != self.piece_count) {
return false;
}
for (pieces, 0..) |piece_data, i| {
if (piece_data.index != i) {
return false;
}
const expected_hash = self.piece_hashes[i];
if (!try HashUtils.verify(piece_data.data, expected_hash)) {
return false;
}
}
return true;
}
};
/// Individual piece data with metadata
pub const PieceData = struct {
index: u32,
data: []const u8,
hash: PieceHash,
/// Create piece data
pub fn create(index: u32, data: []const u8) Error!PieceData {
const hash = try HashUtils.sha256(data);
return PieceData{
.index = index,
.data = data,
.hash = hash,
};
}
/// Verify piece integrity
pub fn verify(self: PieceData) Error!bool {
return HashUtils.verify(self.data, self.hash);
}
};
/// Hash verification result
pub const VerificationResult = struct {
is_valid: bool,
expected_hash: PieceHash,
actual_hash: PieceHash,
piece_index: ?u32,
/// Create successful verification result
pub fn success(piece_index: u32, expected_hash: PieceHash, actual_hash: PieceHash) VerificationResult {
return .{
.is_valid = true,
.expected_hash = expected_hash,
.actual_hash = actual_hash,
.piece_index = piece_index,
};
}
/// Create failed verification result
pub fn failure(piece_index: u32, expected_hash: PieceHash, actual_hash: PieceHash) VerificationResult {
return .{
.is_valid = false,
.expected_hash = expected_hash,
.actual_hash = actual_hash,
.piece_index = piece_index,
};
}
};
/// Hash pool for managing hash computations
pub const HashPool = struct {
allocator: mem.Allocator,
pub fn init(allocator: mem.Allocator) HashPool {
return HashPool{
.allocator = allocator,
};
}
/// Verify multiple pieces efficiently
pub fn verifyPieces(
self: HashPool,
file_metadata: FileMetadata,
piece_datas: []const PieceData,
) Error!VerificationBatch {
var results: std.ArrayList(VerificationResult) = .{};
errdefer results.deinit(self.allocator);
const start_time = std.time.milliTimestamp();
var valid_count: u32 = 0;
for (piece_datas, 0..) |piece_data, i| {
const expected_hash = file_metadata.piece_hashes[i];
const is_valid = try HashUtils.verify(piece_data.data, expected_hash);
if (is_valid) {
try results.append(self.allocator, VerificationResult.success(
piece_data.index,
expected_hash,
piece_data.hash,
));
valid_count += 1;
} else {
const actual_hash = try HashUtils.sha256(piece_data.data);
try results.append(self.allocator, VerificationResult.failure(
piece_data.index,
expected_hash,
actual_hash,
));
}
}
const end_time = std.time.milliTimestamp();
const verification_time = @as(u64, @intCast(end_time - start_time));
return VerificationBatch{
.results = results,
.total_pieces = piece_datas.len,
.valid_pieces = valid_count,
.verification_time_ms = verification_time,
.allocator = self.allocator,
};
}
/// Generate content address for file
pub fn generateContentAddress(_: HashPool, metadata: FileMetadata) Error!ContentHash {
return HashUtils.metadataHash(metadata);
}
};
/// Incremental verification for streaming data
pub const IncrementalVerifier = struct {
hasher: crypto.hash.sha2.Sha256,
expected_hash: PieceHash,
piece_index: u32,
verified_bytes: u64,
total_bytes: u64,
allocator: mem.Allocator,
pub fn init(expected_hash: PieceHash, piece_index: u32, total_bytes: usize, allocator: mem.Allocator) IncrementalVerifier {
return IncrementalVerifier{
.hasher = crypto.hash.sha2.Sha256.init(.{}),
.expected_hash = expected_hash,
.piece_index = piece_index,
.verified_bytes = 0,
.total_bytes = @as(u64, @intCast(total_bytes)),
.allocator = allocator,
};
}
/// Update with new data chunk
pub fn update(self: *IncrementalVerifier, data: []const u8) Error!void {
self.hasher.update(data);
self.verified_bytes += data.len;
}
/// Finalize verification
pub fn finalize(self: *IncrementalVerifier) Error!VerificationResult {
var actual_hash: PieceHash = undefined;
self.hasher.final(&actual_hash);
const is_valid = mem.eql(u8, &actual_hash, &self.expected_hash);
if (is_valid) {
return VerificationResult.success(self.piece_index, self.expected_hash, actual_hash);
} else {
return VerificationResult.failure(self.piece_index, self.expected_hash, actual_hash);
}
}
/// Get verification progress (0.0 to 1.0)
pub fn getProgress(self: IncrementalVerifier) f32 {
if (self.total_bytes == 0) return 1.0;
return @as(f32, @floatFromInt(self.verified_bytes)) / @as(f32, @floatFromInt(self.total_bytes));
}
/// Check if verification is complete
pub fn isComplete(self: IncrementalVerifier) bool {
return self.verified_bytes >= self.total_bytes;
}
};
/// Batch verification results
pub const VerificationBatch = struct {
results: std.ArrayList(VerificationResult),
total_pieces: usize,
valid_pieces: u32,
verification_time_ms: u64,
allocator: mem.Allocator,
/// Get verification success rate
pub fn successRate(self: VerificationBatch) f32 {
if (self.total_pieces == 0) return 0.0;
return @as(f32, @floatFromInt(self.valid_pieces)) / @as(f32, @floatFromInt(self.total_pieces));
}
/// Check if all pieces are valid
pub fn isCompleteSuccess(self: VerificationBatch) bool {
return self.valid_pieces == @as(u32, @intCast(self.total_pieces));
}
/// Get list of failed piece indices
/// NOTE: Caller must free returned slice with allocator.free()
pub fn getFailedPieces(self: VerificationBatch) ![]u32 {
var failed: std.ArrayList(u32) = .{};
errdefer failed.deinit(self.allocator);
for (self.results.items) |result| {
if (!result.is_valid) {
if (result.piece_index) |index| {
try failed.append(self.allocator, index);
}
}
}
return failed.toOwnedSlice(self.allocator);
}
/// Get verification performance metrics
pub fn getPerformanceMetrics(self: VerificationBatch) VerificationMetrics {
const throughput = if (self.verification_time_ms > 0)
@as(f32, @floatFromInt(self.total_pieces)) / (@as(f32, @floatFromInt(self.verification_time_ms)) / 1000.0)
else
0.0;
return VerificationMetrics{
.total_pieces = self.total_pieces,
.valid_pieces = self.valid_pieces,
.verification_time_ms = self.verification_time_ms,
.throughput_pieces_per_second = throughput,
.success_rate = self.successRate(),
};
}
pub fn deinit(self: *VerificationBatch) void {
self.results.deinit(self.allocator);
}
};
/// Verification performance metrics
pub const VerificationMetrics = struct {
total_pieces: usize,
valid_pieces: u32,
verification_time_ms: u64,
throughput_pieces_per_second: f32,
success_rate: f32,
/// Check if verification performance is acceptable
pub fn isPerformanceAcceptable(self: VerificationMetrics, min_throughput: f32) bool {
return self.throughput_pieces_per_second >= min_throughput and self.success_rate >= 0.95;
}
};
// Testing functions
test "hash utilities basic operations" {
const test_data = "Hello, World!";
const hash = try HashUtils.sha256(test_data);
const is_valid = try HashUtils.verify(test_data, hash);
try testing.expect(is_valid);
// Test with wrong data
const wrong_data = "Hello, World";
const is_invalid = try HashUtils.verify(wrong_data, hash);
try testing.expect(!is_invalid);
}
test "hash hex conversion" {
const test_data = "Test data for hex conversion";
const hash = try HashUtils.sha256(test_data);
const hex_str = try HashUtils.toHex(hash, testing.allocator);
defer testing.allocator.free(hex_str);
const parsed_hash = try HashUtils.fromHex(hex_str);
try testing.expect(HashUtils.equal(hash, parsed_hash));
}
test "file metadata hashing" {
const allocator = testing.allocator;
const piece_hashes = try allocator.alloc(PieceHash, 3);
for (piece_hashes) |*hash| {
hash.* = try HashUtils.random(allocator);
}
const metadata = try FileMetadata.create(
"test_file.txt",
1024,
piece_hashes,
allocator,
);
defer allocator.free(metadata.name); // FileMetadata.create allocates name
const content_hash = try HashUtils.metadataHash(metadata);
try testing.expect(content_hash.len == 32);
allocator.free(piece_hashes);
}
test "piece data creation and verification" {
const test_data = "This is test piece data";
const piece = try PieceData.create(0, test_data);
const is_valid = try piece.verify();
try testing.expect(is_valid);
// Test with tampered data - create a piece with original hash but different data
const tampered_data = "This is tampered piece data";
const tampered_piece = PieceData{
.index = 0,
.data = tampered_data,
.hash = piece.hash, // Use original hash with different data
};
const is_invalid = try tampered_piece.verify();
try testing.expect(!is_invalid); // Should fail verification
}
test "hash pool verification" {
const allocator = testing.allocator;
const pool = HashPool.init(allocator);
// Create test metadata
const piece_hashes = try allocator.alloc(PieceHash, 2);
piece_hashes[0] = try HashUtils.sha256("piece 0 data");
piece_hashes[1] = try HashUtils.sha256("piece 1 data");
const metadata = try FileMetadata.create("test.bin", 32, piece_hashes, allocator);
defer allocator.free(metadata.name); // FileMetadata.create allocates name
// Create test pieces
var pieces: std.ArrayList(PieceData) = .{};
try pieces.append(allocator, try PieceData.create(0, "piece 0 data"));
try pieces.append(allocator, try PieceData.create(1, "piece 1 data"));
// Verify pieces
var batch = try pool.verifyPieces(metadata, pieces.items);
defer batch.deinit();
try testing.expect(batch.isCompleteSuccess());
try testing.expectEqual(@as(f32, 1.0), batch.successRate());
pieces.deinit(allocator);
allocator.free(piece_hashes);
}
test "content hash generation" {
const allocator = testing.allocator;
// Create piece hashes
var piece_hashes: std.ArrayList(PieceHash) = .{};
try piece_hashes.append(allocator, try HashUtils.random(allocator));
try piece_hashes.append(allocator, try HashUtils.random(allocator));
try piece_hashes.append(allocator, try HashUtils.random(allocator));
const content_hash = try HashUtils.contentHash(piece_hashes.items);
try testing.expect(content_hash.len == 32);
piece_hashes.deinit(allocator);
}

6815
src/files/manager.zig Normal file

File diff suppressed because it is too large Load Diff

778
src/files/mock_fs.zig Normal file
View File

@@ -0,0 +1,778 @@
//! Mock Filesystem for Testing
//!
//! Provides an in-memory filesystem implementation for unit testing file operations
//! without touching the real filesystem. This enables deterministic, fast, and
//! isolated testing of file-related code.
//!
//! Usage:
//! ```zig
//! var mock_fs = MockFS.init(allocator);
//! defer mock_fs.deinit();
//!
//! // Create a file with content
//! try mock_fs.writeFile("/test/file.txt", "Hello, World!");
//!
//! // Read the file back
//! const content = try mock_fs.readFile(allocator, "/test/file.txt");
//! defer allocator.free(content);
//! ```
const std = @import("std");
const Allocator = std.mem.Allocator;
/// Error types for MockFS operations
pub const MockFSError = error{
FileNotFound,
DirectoryNotFound,
FileAlreadyExists,
DirectoryAlreadyExists,
NotAFile,
NotADirectory,
InvalidPath,
OutOfMemory,
PermissionDenied,
DiskFull,
IOError,
};
/// Represents a file in the mock filesystem
pub const MockFile = struct {
allocator: Allocator,
data: []u8,
created_at: i64,
modified_at: i64,
is_readonly: bool = false,
pub fn init(allocator: Allocator) MockFile {
return .{
.allocator = allocator,
.data = &[_]u8{},
.created_at = std.time.timestamp(),
.modified_at = std.time.timestamp(),
};
}
pub fn deinit(self: *MockFile) void {
if (self.data.len > 0) {
self.allocator.free(self.data);
}
}
pub fn size(self: *const MockFile) usize {
return self.data.len;
}
pub fn setContent(self: *MockFile, content: []const u8) !void {
// FIX: Allocate new data BEFORE freeing old to prevent use-after-free
// if dupe fails. Previously, if dupe failed after free, self.data
// would be a dangling pointer.
const new_data = try self.allocator.dupe(u8, content);
if (self.data.len > 0) {
self.allocator.free(self.data);
}
self.data = new_data;
self.modified_at = std.time.timestamp();
}
pub fn resize(self: *MockFile, new_size: usize) !void {
if (new_size == self.data.len) return;
const new_data = try self.allocator.alloc(u8, new_size);
const copy_len = @min(self.data.len, new_size);
if (copy_len > 0) {
@memcpy(new_data[0..copy_len], self.data[0..copy_len]);
}
// Zero-fill any new bytes
if (new_size > self.data.len) {
@memset(new_data[self.data.len..], 0);
}
if (self.data.len > 0) {
self.allocator.free(self.data);
}
self.data = new_data;
self.modified_at = std.time.timestamp();
}
};
/// Mock file handle for read/write operations
pub const MockFileHandle = struct {
fs: *MockFS,
path: []const u8,
position: usize = 0,
read_only: bool,
/// Read data from current position
pub fn read(self: *MockFileHandle, buffer: []u8) MockFSError!usize {
const file = self.fs.files.get(self.path) orelse return MockFSError.FileNotFound;
const content = file.data;
if (self.position >= content.len) {
return 0; // EOF
}
const available = content.len - self.position;
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[self.position..][0..to_read]);
self.position += to_read;
return to_read;
}
/// Read at specific offset (like pread)
pub fn pread(self: *MockFileHandle, buffer: []u8, offset: u64) MockFSError!usize {
const file = self.fs.files.get(self.path) orelse return MockFSError.FileNotFound;
const content = file.data;
const off: usize = @intCast(@min(offset, content.len));
if (off >= content.len) {
return 0;
}
const available = content.len - off;
const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[off..][0..to_read]);
return to_read;
}
/// Write data at current position
pub fn write(self: *MockFileHandle, data: []const u8) MockFSError!usize {
if (self.read_only) return MockFSError.PermissionDenied;
const file = self.fs.files.getPtr(self.path) orelse return MockFSError.FileNotFound;
// Extend file if necessary
if (self.position + data.len > file.data.len) {
const new_len = self.position + data.len;
file.resize(new_len) catch return MockFSError.OutOfMemory;
}
// Copy data
@memcpy(file.data[self.position..][0..data.len], data);
self.position += data.len;
file.modified_at = std.time.timestamp();
return data.len;
}
/// Write at specific offset (like pwrite)
pub fn pwrite(self: *MockFileHandle, data: []const u8, offset: u64) MockFSError!usize {
if (self.read_only) return MockFSError.PermissionDenied;
const file = self.fs.files.getPtr(self.path) orelse return MockFSError.FileNotFound;
const off: usize = @intCast(offset);
// Extend file if necessary
if (off + data.len > file.data.len) {
const new_len = off + data.len;
file.resize(new_len) catch return MockFSError.OutOfMemory;
}
// Copy data
@memcpy(file.data[off..][0..data.len], data);
file.modified_at = std.time.timestamp();
return data.len;
}
/// Seek to position
pub fn seekTo(self: *MockFileHandle, position: u64) void {
self.position = @intCast(position);
}
/// Get current position
pub fn getPos(self: *const MockFileHandle) u64 {
return self.position;
}
/// Get file size
pub fn stat(self: *const MockFileHandle) MockFSError!MockFileStat {
const file = self.fs.files.get(self.path) orelse return MockFSError.FileNotFound;
return MockFileStat{
.size = file.data.len,
.created_at = file.created_at,
.modified_at = file.modified_at,
};
}
/// Set file end position (truncate/extend)
pub fn setEndPos(self: *MockFileHandle, size: u64) MockFSError!void {
if (self.read_only) return MockFSError.PermissionDenied;
const file = self.fs.files.getPtr(self.path) orelse return MockFSError.FileNotFound;
file.resize(@intCast(size)) catch return MockFSError.OutOfMemory;
}
/// Sync (no-op for mock)
pub fn sync(self: *MockFileHandle) void {
_ = self;
}
/// Close handle (no-op for mock since we don't track open handles)
pub fn close(self: *MockFileHandle) void {
_ = self;
}
};
/// File statistics
pub const MockFileStat = struct {
size: usize,
created_at: i64,
modified_at: i64,
};
/// In-memory mock filesystem
pub const MockFS = struct {
allocator: Allocator,
files: std.StringHashMap(MockFile),
directories: std.StringHashMap(void),
/// Simulated disk space limit (0 = unlimited)
disk_limit: usize = 0,
/// Current total size of all files
disk_used: usize = 0,
/// Inject errors for testing error handling
inject_error: ?MockFSError = null,
pub fn init(allocator: Allocator) MockFS {
var fs = MockFS{
.allocator = allocator,
.files = std.StringHashMap(MockFile).init(allocator),
.directories = std.StringHashMap(void).init(allocator),
};
// Root directory always exists - allocate the key so it can be freed in deinit
const root = allocator.dupe(u8, "/") catch return fs;
fs.directories.put(root, {}) catch {
allocator.free(root);
};
return fs;
}
pub fn deinit(self: *MockFS) void {
var file_iter = self.files.iterator();
while (file_iter.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
entry.value_ptr.deinit();
}
self.files.deinit();
var dir_iter = self.directories.iterator();
while (dir_iter.next()) |entry| {
self.allocator.free(entry.key_ptr.*);
}
self.directories.deinit();
}
/// Set disk space limit for testing disk full scenarios
pub fn setDiskLimit(self: *MockFS, limit: usize) void {
self.disk_limit = limit;
}
/// Inject an error to be returned on the next operation
pub fn injectError(self: *MockFS, err: MockFSError) void {
self.inject_error = err;
}
/// Clear injected error
pub fn clearError(self: *MockFS) void {
self.inject_error = null;
}
fn checkError(self: *MockFS) MockFSError!void {
if (self.inject_error) |err| {
self.inject_error = null;
return err;
}
}
/// Create a directory (and parents if needed)
pub fn makeDir(self: *MockFS, path: []const u8) MockFSError!void {
try self.checkError();
// Normalize path
const norm_path = try self.normalizePath(path);
if (self.directories.contains(norm_path)) {
self.allocator.free(norm_path);
return; // Already exists, success
}
// Create parent directories
var parent_end = norm_path.len;
while (parent_end > 1) {
parent_end -= 1;
if (norm_path[parent_end] == '/') {
const parent = norm_path[0..parent_end];
if (!self.directories.contains(parent)) {
const parent_copy = self.allocator.dupe(u8, parent) catch return MockFSError.OutOfMemory;
self.directories.put(parent_copy, {}) catch {
self.allocator.free(parent_copy);
return MockFSError.OutOfMemory;
};
}
}
}
self.directories.put(norm_path, {}) catch {
self.allocator.free(norm_path);
return MockFSError.OutOfMemory;
};
}
/// Create a file (parent directory must exist)
pub fn createFile(self: *MockFS, path: []const u8) MockFSError!MockFileHandle {
try self.checkError();
const norm_path = try self.normalizePath(path);
if (self.files.contains(norm_path)) {
self.allocator.free(norm_path);
return MockFSError.FileAlreadyExists;
}
var file = MockFile.init(self.allocator);
self.files.put(norm_path, file) catch {
file.deinit();
self.allocator.free(norm_path);
return MockFSError.OutOfMemory;
};
return MockFileHandle{
.fs = self,
.path = norm_path,
.read_only = false,
};
}
/// Open an existing file
pub fn openFile(self: *MockFS, path: []const u8, read_only: bool) MockFSError!MockFileHandle {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
if (!self.files.contains(norm_path)) {
return MockFSError.FileNotFound;
}
// Get the stored key (which we own)
const entry = self.files.getEntry(norm_path) orelse return MockFSError.FileNotFound;
return MockFileHandle{
.fs = self,
.path = entry.key_ptr.*,
.read_only = read_only,
};
}
/// Write entire content to a file (convenience method)
pub fn writeFile(self: *MockFS, path: []const u8, content: []const u8) MockFSError!void {
try self.checkError();
// Check disk space
if (self.disk_limit > 0 and self.disk_used + content.len > self.disk_limit) {
return MockFSError.DiskFull;
}
const norm_path = try self.normalizePath(path);
// Create parent directories
var last_slash: usize = 0;
for (norm_path, 0..) |c, i| {
if (c == '/') last_slash = i;
}
if (last_slash > 0) {
try self.makeDir(norm_path[0..last_slash]);
}
if (self.files.getPtr(norm_path)) |existing| {
// Update existing file
self.disk_used -= existing.data.len;
existing.setContent(content) catch return MockFSError.OutOfMemory;
self.disk_used += content.len;
self.allocator.free(norm_path);
} else {
// Create new file
var file = MockFile.init(self.allocator);
file.setContent(content) catch {
file.deinit();
self.allocator.free(norm_path);
return MockFSError.OutOfMemory;
};
self.files.put(norm_path, file) catch {
file.deinit();
self.allocator.free(norm_path);
return MockFSError.OutOfMemory;
};
self.disk_used += content.len;
}
}
/// Read entire file content
pub fn readFile(self: *MockFS, allocator: Allocator, path: []const u8) MockFSError![]u8 {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
const file = self.files.get(norm_path) orelse return MockFSError.FileNotFound;
const content = allocator.dupe(u8, file.data) catch return MockFSError.OutOfMemory;
return content;
}
/// Check if file exists
pub fn fileExists(self: *MockFS, path: []const u8) bool {
const norm_path = self.normalizePath(path) catch return false;
defer self.allocator.free(norm_path);
return self.files.contains(norm_path);
}
/// Check if directory exists
pub fn dirExists(self: *MockFS, path: []const u8) bool {
const norm_path = self.normalizePath(path) catch return false;
defer self.allocator.free(norm_path);
return self.directories.contains(norm_path);
}
/// Delete a file
pub fn deleteFile(self: *MockFS, path: []const u8) MockFSError!void {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
const entry = self.files.fetchRemove(norm_path) orelse return MockFSError.FileNotFound;
self.disk_used -= entry.value.data.len;
self.allocator.free(entry.key);
var file = entry.value;
file.deinit();
}
/// Rename/move a file
pub fn rename(self: *MockFS, old_path: []const u8, new_path: []const u8) MockFSError!void {
try self.checkError();
const old_norm = try self.normalizePath(old_path);
defer self.allocator.free(old_norm);
const new_norm = try self.normalizePath(new_path);
const entry = self.files.fetchRemove(old_norm) orelse {
self.allocator.free(new_norm);
return MockFSError.FileNotFound;
};
self.allocator.free(entry.key);
self.files.put(new_norm, entry.value) catch {
self.allocator.free(new_norm);
return MockFSError.OutOfMemory;
};
}
/// Get file stats
pub fn stat(self: *MockFS, path: []const u8) MockFSError!MockFileStat {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
const file = self.files.get(norm_path) orelse return MockFSError.FileNotFound;
return MockFileStat{
.size = file.data.len,
.created_at = file.created_at,
.modified_at = file.modified_at,
};
}
/// List files in directory
pub fn listDir(self: *MockFS, allocator: Allocator, path: []const u8) MockFSError![][]const u8 {
try self.checkError();
const norm_path = try self.normalizePath(path);
defer self.allocator.free(norm_path);
if (!self.directories.contains(norm_path)) {
return MockFSError.DirectoryNotFound;
}
const prefix_len = if (std.mem.eql(u8, norm_path, "/")) 1 else norm_path.len + 1;
// Count matching entries first
var count: usize = 0;
var iter = self.files.iterator();
while (iter.next()) |entry| {
const file_path = entry.key_ptr.*;
if (std.mem.startsWith(u8, file_path, norm_path) and
file_path.len > prefix_len and
std.mem.indexOfScalar(u8, file_path[prefix_len..], '/') == null)
{
count += 1;
}
}
// Allocate result array
const entries = allocator.alloc([]const u8, count) catch return MockFSError.OutOfMemory;
errdefer allocator.free(entries);
// Fill entries
var idx: usize = 0;
iter = self.files.iterator();
while (iter.next()) |entry| {
const file_path = entry.key_ptr.*;
if (std.mem.startsWith(u8, file_path, norm_path) and
file_path.len > prefix_len and
std.mem.indexOfScalar(u8, file_path[prefix_len..], '/') == null)
{
entries[idx] = allocator.dupe(u8, file_path[prefix_len..]) catch {
// Free already allocated entries
for (entries[0..idx]) |e| allocator.free(e);
return MockFSError.OutOfMemory;
};
idx += 1;
}
}
return entries;
}
/// Normalize path (remove trailing slashes, ensure leading slash)
fn normalizePath(self: *MockFS, path: []const u8) MockFSError![]u8 {
if (path.len == 0) return MockFSError.InvalidPath;
// First pass: calculate the normalized length
var len: usize = 0;
var prev_slash = false;
var ends_with_slash = false;
// Account for leading slash if missing
if (path[0] != '/') {
len = 1;
}
// Count characters after normalization
for (path) |c| {
if (c == '/') {
if (!prev_slash) {
len += 1;
ends_with_slash = true;
}
prev_slash = true;
} else {
len += 1;
prev_slash = false;
ends_with_slash = false;
}
}
// Remove trailing slash (unless root)
if (len > 1 and ends_with_slash) {
len -= 1;
}
// Allocate exact size needed
const result = self.allocator.alloc(u8, len) catch return MockFSError.OutOfMemory;
// Second pass: fill the buffer
var idx: usize = 0;
// Ensure leading slash
if (path[0] != '/') {
result[idx] = '/';
idx += 1;
}
// Copy path, normalizing double slashes
prev_slash = false;
for (path) |c| {
if (idx >= len) break;
if (c == '/') {
if (!prev_slash) {
result[idx] = '/';
idx += 1;
}
prev_slash = true;
} else {
result[idx] = c;
idx += 1;
prev_slash = false;
}
}
return result;
}
};
// ============================================================================
// Tests
// ============================================================================
test "MockFS: create and read file" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/test.txt", "Hello, World!");
const content = try fs.readFile(allocator, "/test.txt");
defer allocator.free(content);
try std.testing.expectEqualStrings("Hello, World!", content);
}
test "MockFS: file handle operations" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
// Create and write via handle
var handle = try fs.createFile("/data.bin");
_ = try handle.write("First part");
_ = try handle.write(" Second part");
handle.close();
// Read back
var read_handle = try fs.openFile("/data.bin", true);
var buffer: [100]u8 = undefined;
const n = try read_handle.read(&buffer);
try std.testing.expectEqualStrings("First part Second part", buffer[0..n]);
}
test "MockFS: pread/pwrite operations" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/random.bin", "0123456789");
var handle = try fs.openFile("/random.bin", false);
// pwrite at offset 5
_ = try handle.pwrite("XXXXX", 5);
// pread to verify
var buffer: [10]u8 = undefined;
const n = try handle.pread(&buffer, 0);
try std.testing.expectEqualStrings("01234XXXXX", buffer[0..n]);
}
test "MockFS: directory operations" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.makeDir("/foo/bar/baz");
try std.testing.expect(fs.dirExists("/foo"));
try std.testing.expect(fs.dirExists("/foo/bar"));
try std.testing.expect(fs.dirExists("/foo/bar/baz"));
}
test "MockFS: file not found" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
const result = fs.readFile(allocator, "/nonexistent.txt");
try std.testing.expectError(MockFSError.FileNotFound, result);
}
test "MockFS: disk full simulation" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
fs.setDiskLimit(100);
try fs.writeFile("/small.txt", "Small file");
try std.testing.expectEqual(@as(usize, 10), fs.disk_used);
// This should fail
const result = fs.writeFile("/large.txt", "A" ** 200);
try std.testing.expectError(MockFSError.DiskFull, result);
}
test "MockFS: error injection" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/test.txt", "content");
// Inject error
fs.injectError(MockFSError.IOError);
// Next operation should fail
const result = fs.readFile(allocator, "/test.txt");
try std.testing.expectError(MockFSError.IOError, result);
// Subsequent operations should work
const content = try fs.readFile(allocator, "/test.txt");
defer allocator.free(content);
try std.testing.expectEqualStrings("content", content);
}
test "MockFS: rename file" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/old.txt", "content");
try fs.rename("/old.txt", "/new.txt");
try std.testing.expect(!fs.fileExists("/old.txt"));
try std.testing.expect(fs.fileExists("/new.txt"));
const content = try fs.readFile(allocator, "/new.txt");
defer allocator.free(content);
try std.testing.expectEqualStrings("content", content);
}
test "MockFS: delete file" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/to_delete.txt", "content");
try std.testing.expect(fs.fileExists("/to_delete.txt"));
try fs.deleteFile("/to_delete.txt");
try std.testing.expect(!fs.fileExists("/to_delete.txt"));
}
test "MockFS: file stats" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/stats.txt", "Hello!");
const s = try fs.stat("/stats.txt");
try std.testing.expectEqual(@as(usize, 6), s.size);
try std.testing.expect(s.created_at > 0);
try std.testing.expect(s.modified_at >= s.created_at);
}
test "MockFS: list directory" {
const allocator = std.testing.allocator;
var fs = MockFS.init(allocator);
defer fs.deinit();
try fs.writeFile("/dir/file1.txt", "1");
try fs.writeFile("/dir/file2.txt", "2");
try fs.writeFile("/dir/subdir/file3.txt", "3");
const entries = try fs.listDir(allocator, "/dir");
defer {
for (entries) |e| allocator.free(e);
allocator.free(entries);
}
try std.testing.expectEqual(@as(usize, 2), entries.len);
}

1176
src/files/path_security.zig Normal file

File diff suppressed because it is too large Load Diff

472
src/files/peer_metrics.zig Normal file
View File

@@ -0,0 +1,472 @@
//! Per-peer metrics tracking for adaptive request pipelining
//!
//! Tracks RTT, bandwidth, and calculates optimal queue depth using
//! Bandwidth-Delay Product (BDP) measurements.
const std = @import("std");
const core = @import("core");
const Error = core.errors.Error;
/// Per-peer metrics for adaptive pipelining
pub const PeerMetrics = struct {
/// Peer identifier
peer_id: [32]u8,
// Measured values (exponential moving averages)
/// Round-trip time in milliseconds
rtt_ms: f64 = 10.0, // Default 10ms
/// Measured bandwidth in bytes per second
bandwidth_bps: f64 = 100 * 1024 * 1024, // Default 100 MB/s
/// Piece loss/failure rate (0.0 to 1.0)
loss_rate: f64 = 0.0,
// Derived values
/// Bandwidth-delay product in bytes
bdp_bytes: u64 = 0,
/// Calculated optimal queue depth (pending requests)
/// CASCADE PERF: Increased from 8 to 32 for high-throughput cascade distribution
optimal_queue_depth: u32 = 32,
// State tracking
/// Current number of pending requests
current_pending: u32 = 0,
/// Consecutive timeout count (for AIMD)
consecutive_timeouts: u32 = 0,
/// Total successful pieces from this peer
successful_pieces: u64 = 0,
/// Total failed pieces from this peer
failed_pieces: u64 = 0,
/// Pieces since last AIMD increase (for additive increase)
pieces_since_increase: u64 = 0,
// Timing for measurements
/// Timestamp of last RTT probe sent
last_probe_sent_ns: i128 = 0,
/// Timestamp of last piece request (for RTT measurement)
last_request_time_ns: i128 = 0,
/// Bytes received since last bandwidth calculation
bytes_since_last_calc: u64 = 0,
/// Timestamp of last bandwidth calculation
last_bandwidth_calc_ns: i128 = 0,
// Configuration
/// Piece size for BDP calculation
piece_size: u64,
/// Minimum queue depth
/// THROUGHPUT FIX: Increased from 8 to 16. Balance between:
/// - Too low (8): Starves pipeline, limits throughput
/// - Too high (32+): Can overwhelm peers, causing timeouts
min_queue_depth: u32 = 16,
/// Maximum queue depth
/// CASCADE PERF: Increased from 32 to 128 for high-throughput cascade
max_queue_depth: u32 = 128,
/// EWMA smoothing factor for RTT (0.125 = 1/8, standard TCP value)
rtt_alpha: f64 = 0.125,
/// EWMA smoothing factor for bandwidth
bandwidth_alpha: f64 = 0.25,
pub fn init(peer_id: [32]u8, piece_size: u64) PeerMetrics {
var metrics = PeerMetrics{
.peer_id = peer_id,
.piece_size = piece_size,
.last_bandwidth_calc_ns = std.time.nanoTimestamp(),
};
metrics.recalculateBdp();
return metrics;
}
/// Record a request being sent (for RTT measurement)
pub fn recordRequestSent(self: *PeerMetrics) void {
self.last_request_time_ns = std.time.nanoTimestamp();
self.current_pending += 1;
}
/// Record a response received with timing for RTT calculation
pub fn recordResponseReceived(self: *PeerMetrics, bytes: u64, success: bool) void {
const now = std.time.nanoTimestamp();
if (self.current_pending > 0) {
self.current_pending -= 1;
}
if (success) {
self.successful_pieces += 1;
self.consecutive_timeouts = 0;
// Update RTT if we have a valid request timestamp
if (self.last_request_time_ns > 0) {
const elapsed_ns = now - self.last_request_time_ns;
const elapsed_ms = @as(f64, @floatFromInt(elapsed_ns)) / 1_000_000.0;
if (elapsed_ms > 0 and elapsed_ms < 60000) { // Sanity check: < 60 seconds
self.updateRtt(elapsed_ms);
}
}
// Update bandwidth measurement
self.bytes_since_last_calc += bytes;
const time_since_calc = now - self.last_bandwidth_calc_ns;
// Calculate bandwidth every 100ms or after 10MB
if (time_since_calc > 100_000_000 or self.bytes_since_last_calc > 10 * 1024 * 1024) {
if (time_since_calc > 0) {
const elapsed_sec = @as(f64, @floatFromInt(time_since_calc)) / 1_000_000_000.0;
const measured_bps = @as(f64, @floatFromInt(self.bytes_since_last_calc)) / elapsed_sec;
self.updateBandwidth(measured_bps);
}
self.bytes_since_last_calc = 0;
self.last_bandwidth_calc_ns = now;
}
// Update loss rate (exponential decay towards 0)
self.loss_rate = self.loss_rate * 0.99;
// AIMD: Additive increase after successful epoch
// An epoch = optimal_queue_depth successful pieces
self.pieces_since_increase += 1;
if (self.pieces_since_increase >= self.optimal_queue_depth) {
self.increaseQueueDepth();
self.pieces_since_increase = 0;
}
} else {
self.failed_pieces += 1;
self.consecutive_timeouts += 1;
// Update loss rate (exponential increase)
self.loss_rate = self.loss_rate * 0.9 + 0.1;
// AIMD: Reset increase counter on failure
self.pieces_since_increase = 0;
}
// Recalculate optimal queue depth
self.recalculateBdp();
}
/// Record a request rejection (peer was busy) - less severe than timeout
/// THROUGHPUT FIX: Helps peer selection prefer other peers when one is overloaded
pub fn recordRequestRejected(self: *PeerMetrics) void {
if (self.current_pending > 0) {
self.current_pending -= 1;
}
// Mild loss rate increase (half of full failure)
self.loss_rate = self.loss_rate * 0.95 + 0.05;
// Don't count as failed_piece or increase consecutive_timeouts
// since this is expected behavior when a peer is busy
}
/// Update RTT with exponential moving average
pub fn updateRtt(self: *PeerMetrics, sample_ms: f64) void {
if (self.rtt_ms == 0) {
self.rtt_ms = sample_ms;
} else {
// EWMA: new = (1 - alpha) * old + alpha * sample
self.rtt_ms = (1.0 - self.rtt_alpha) * self.rtt_ms + self.rtt_alpha * sample_ms;
}
self.recalculateBdp();
}
/// Update bandwidth with exponential moving average
pub fn updateBandwidth(self: *PeerMetrics, sample_bps: f64) void {
if (self.bandwidth_bps == 0) {
self.bandwidth_bps = sample_bps;
} else {
self.bandwidth_bps = (1.0 - self.bandwidth_alpha) * self.bandwidth_bps + self.bandwidth_alpha * sample_bps;
}
self.recalculateBdp();
}
/// Recalculate BDP and optimal queue depth
fn recalculateBdp(self: *PeerMetrics) void {
// BDP = Bandwidth (bytes/sec) * RTT (sec)
const rtt_sec = self.rtt_ms / 1000.0;
const bdp = self.bandwidth_bps * rtt_sec;
self.bdp_bytes = @intFromFloat(@max(0, bdp));
// Optimal pending = BDP / piece_size, with min/max bounds
const piece_size_f = @as(f64, @floatFromInt(self.piece_size));
var optimal: f64 = bdp / piece_size_f;
// Apply loss rate penalty
if (self.loss_rate > 0.01) {
optimal = optimal * (1.0 - self.loss_rate);
}
// Clamp to bounds
const optimal_u32 = @as(u32, @intFromFloat(@max(1, @min(optimal, 100))));
self.optimal_queue_depth = @max(self.min_queue_depth, @min(self.max_queue_depth, optimal_u32));
}
/// Get current optimal queue depth (considers AIMD backoff)
pub fn getEffectiveQueueDepth(self: *const PeerMetrics) u32 {
var depth = self.optimal_queue_depth;
// CASCADE PERF: Gentler backoff to prevent cascade death spiral
// Old: halving per timeout (8 -> 4 -> 2 -> 1) - too aggressive
// New: 25% reduction per timeout, capped at 3 reductions (8 -> 6 -> 4.5 -> 3.3)
// This maintains usable throughput even during temporary congestion
if (self.consecutive_timeouts > 0) {
const reductions = @min(self.consecutive_timeouts, 3);
var i: u32 = 0;
while (i < reductions) : (i += 1) {
depth = depth - (depth / 4); // 25% reduction each time
}
}
return @max(self.min_queue_depth, depth);
}
/// Check if we can send another request to this peer
pub fn canSendRequest(self: *const PeerMetrics) bool {
return self.current_pending < self.getEffectiveQueueDepth();
}
/// Get number of available request slots
pub fn getAvailableSlots(self: *const PeerMetrics) u32 {
const effective = self.getEffectiveQueueDepth();
if (self.current_pending >= effective) return 0;
return effective - self.current_pending;
}
/// AIMD: Additive increase after successful period
pub fn increaseQueueDepth(self: *PeerMetrics) void {
if (self.optimal_queue_depth < self.max_queue_depth) {
self.optimal_queue_depth += 1;
}
}
/// AIMD: Multiplicative decrease on failure
pub fn decreaseQueueDepth(self: *PeerMetrics) void {
self.optimal_queue_depth = @max(self.min_queue_depth, self.optimal_queue_depth / 2);
}
/// Get peer score for piece assignment (higher = better)
pub fn getScore(self: *const PeerMetrics) f64 {
// Score = bandwidth / (rtt * (current_load + 1))
const load_factor = @as(f64, @floatFromInt(self.current_pending + 1));
const rtt_factor = @max(self.rtt_ms, 0.1); // Avoid division by zero
return self.bandwidth_bps / (rtt_factor * load_factor * 1_000_000.0);
}
/// Format metrics for logging
pub fn format(self: *const PeerMetrics) [128]u8 {
var buf: [128]u8 = undefined;
_ = std.fmt.bufPrint(&buf, "RTT={d:.1}ms BW={d:.1}MB/s BDP={d}KB depth={}/{} pending={}", .{
self.rtt_ms,
self.bandwidth_bps / (1024 * 1024),
self.bdp_bytes / 1024,
self.getEffectiveQueueDepth(),
self.optimal_queue_depth,
self.current_pending,
}) catch {};
return buf;
}
};
/// Manager for tracking metrics across all peers
pub const PeerMetricsManager = struct {
/// Per-peer metrics storage
metrics: std.AutoHashMap([32]u8, PeerMetrics),
/// Default piece size for new peers
piece_size: u64,
/// Allocator
allocator: std.mem.Allocator,
/// Mutex for thread safety
mutex: std.Thread.Mutex = .{},
pub fn init(allocator: std.mem.Allocator, piece_size: u64) PeerMetricsManager {
return .{
.metrics = std.AutoHashMap([32]u8, PeerMetrics).init(allocator),
.piece_size = piece_size,
.allocator = allocator,
};
}
pub fn deinit(self: *PeerMetricsManager) void {
self.metrics.deinit();
}
/// Get or create metrics for a peer
pub fn getOrCreate(self: *PeerMetricsManager, peer_id: [32]u8) Error!*PeerMetrics {
self.mutex.lock();
defer self.mutex.unlock();
const gop = try self.metrics.getOrPut(peer_id);
if (!gop.found_existing) {
gop.value_ptr.* = PeerMetrics.init(peer_id, self.piece_size);
}
return gop.value_ptr;
}
/// Get metrics for a peer (returns null if not found)
pub fn get(self: *PeerMetricsManager, peer_id: [32]u8) ?*PeerMetrics {
self.mutex.lock();
defer self.mutex.unlock();
return self.metrics.getPtr(peer_id);
}
/// Remove a peer
pub fn remove(self: *PeerMetricsManager, peer_id: [32]u8) void {
self.mutex.lock();
defer self.mutex.unlock();
_ = self.metrics.remove(peer_id);
}
/// Record that a peer rejected a request (was busy)
/// THROUGHPUT FIX: Allows peer selection to prefer other peers
pub fn recordRequestRejected(self: *PeerMetricsManager, peer_id: [32]u8) void {
self.mutex.lock();
defer self.mutex.unlock();
if (self.metrics.getPtr(peer_id)) |metrics| {
metrics.recordRequestRejected();
}
}
/// Get the best peer for a piece based on score
pub fn getBestPeer(self: *PeerMetricsManager, available_peers: []const [32]u8) ?[32]u8 {
self.mutex.lock();
defer self.mutex.unlock();
var best_peer: ?[32]u8 = null;
var best_score: f64 = 0;
for (available_peers) |peer_id| {
if (self.metrics.getPtr(peer_id)) |metrics| {
if (metrics.canSendRequest()) {
const score = metrics.getScore();
if (score > best_score) {
best_score = score;
best_peer = peer_id;
}
}
}
}
return best_peer;
}
/// Get total pending across all peers
pub fn getTotalPending(self: *PeerMetricsManager) u32 {
self.mutex.lock();
defer self.mutex.unlock();
var total: u32 = 0;
var iter = self.metrics.valueIterator();
while (iter.next()) |metrics| {
total += metrics.current_pending;
}
return total;
}
/// Get aggregated stats
pub fn getStats(self: *PeerMetricsManager) MetricsStats {
self.mutex.lock();
defer self.mutex.unlock();
var stats = MetricsStats{};
var iter = self.metrics.valueIterator();
while (iter.next()) |metrics| {
stats.peer_count += 1;
stats.total_pending += metrics.current_pending;
stats.total_successful += metrics.successful_pieces;
stats.total_failed += metrics.failed_pieces;
stats.avg_rtt_ms += metrics.rtt_ms;
stats.avg_bandwidth_mbps += metrics.bandwidth_bps / (1024 * 1024);
}
if (stats.peer_count > 0) {
stats.avg_rtt_ms /= @floatFromInt(stats.peer_count);
stats.avg_bandwidth_mbps /= @floatFromInt(stats.peer_count);
}
return stats;
}
};
/// Aggregated metrics statistics
pub const MetricsStats = struct {
peer_count: u32 = 0,
total_pending: u32 = 0,
total_successful: u64 = 0,
total_failed: u64 = 0,
avg_rtt_ms: f64 = 0,
avg_bandwidth_mbps: f64 = 0,
};
// Tests
test "PeerMetrics basic operations" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0x42);
var metrics = PeerMetrics.init(peer_id, 1024 * 1024); // 1MB pieces
// Initial state
try std.testing.expect(metrics.canSendRequest());
try std.testing.expectEqual(@as(u32, 0), metrics.current_pending);
// Send a request
metrics.recordRequestSent();
try std.testing.expectEqual(@as(u32, 1), metrics.current_pending);
// Receive response
metrics.recordResponseReceived(1024 * 1024, true);
try std.testing.expectEqual(@as(u32, 0), metrics.current_pending);
try std.testing.expectEqual(@as(u64, 1), metrics.successful_pieces);
}
test "PeerMetrics RTT measurement" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0x42);
var metrics = PeerMetrics.init(peer_id, 1024 * 1024);
const initial_rtt = metrics.rtt_ms;
// Update RTT with samples
metrics.updateRtt(5.0);
try std.testing.expect(metrics.rtt_ms < initial_rtt); // Should move towards 5ms
metrics.updateRtt(5.0);
metrics.updateRtt(5.0);
metrics.updateRtt(5.0);
try std.testing.expect(metrics.rtt_ms < 8.0); // Should be closer to 5ms
}
test "PeerMetrics AIMD behavior" {
var peer_id: [32]u8 = undefined;
@memset(&peer_id, 0x42);
var metrics = PeerMetrics.init(peer_id, 1024 * 1024);
metrics.optimal_queue_depth = 16;
metrics.min_queue_depth = 2; // Set lower min to allow reduction below 16
// Simulate failures
metrics.recordResponseReceived(0, false);
metrics.recordResponseReceived(0, false);
try std.testing.expect(metrics.consecutive_timeouts == 2);
// With 2 timeouts and 25% reduction each: 16 -> 12 -> 9
try std.testing.expect(metrics.getEffectiveQueueDepth() < 16);
// Simulate success - should reset timeout counter
metrics.recordResponseReceived(1024 * 1024, true);
try std.testing.expectEqual(@as(u32, 0), metrics.consecutive_timeouts);
}
test "PeerMetricsManager operations" {
const allocator = std.testing.allocator;
var manager = PeerMetricsManager.init(allocator, 1024 * 1024);
defer manager.deinit();
var peer1: [32]u8 = undefined;
@memset(&peer1, 0x01);
var peer2: [32]u8 = undefined;
@memset(&peer2, 0x02);
// Get or create
const metrics1 = try manager.getOrCreate(peer1);
try std.testing.expect(metrics1.canSendRequest());
const metrics2 = try manager.getOrCreate(peer2);
try std.testing.expect(metrics2.canSendRequest());
// Stats
const stats = manager.getStats();
try std.testing.expectEqual(@as(u32, 2), stats.peer_count);
}

844
src/files/piece.zig Normal file
View File

@@ -0,0 +1,844 @@
//! Piece selection algorithms and tracking
//!
//! This module implements various piece selection strategies including
//! rarest-first, random, and sequential algorithms for optimal P2P distribution.
const std = @import("std");
const testing = std.testing;
const mem = std.mem;
const math = std.math;
const core = @import("core");
const Error = core.errors.Error;
const hash_mod = @import("hash.zig");
const PieceHash = hash_mod.PieceHash;
/// Piece availability tracking
pub const PieceAvailability = struct {
piece_index: u32,
available_peers: u32,
is_downloaded: bool,
is_verified: bool,
priority: Priority,
pub const Priority = enum(u8) {
low = 0,
normal = 1,
high = 2,
immediate = 3,
};
/// Create availability entry
pub fn create(piece_index: u32, available_peers: u32) PieceAvailability {
return PieceAvailability{
.piece_index = piece_index,
.available_peers = available_peers,
.is_downloaded = false,
.is_verified = false,
.priority = .normal,
};
}
/// Mark piece as downloaded
pub fn markDownloaded(self: *PieceAvailability) void {
self.is_downloaded = true;
self.is_verified = false;
}
/// Mark piece as pending verification (sets is_downloaded without resetting is_verified).
/// Used when a piece is queued for async verification to prevent re-selection,
/// without disturbing a concurrent verification that may have already completed.
pub fn markPendingVerification(self: *PieceAvailability) void {
self.is_downloaded = true;
}
/// Reset downloaded state so piece can be re-requested (e.g. after verification failure)
pub fn resetDownloaded(self: *PieceAvailability) void {
self.is_downloaded = false;
}
/// Mark piece as verified
pub fn markVerified(self: *PieceAvailability) void {
self.is_verified = true;
}
/// Set piece priority
pub fn setPriority(self: *PieceAvailability, priority: Priority) void {
self.priority = priority;
}
/// Check if piece is ready for download
pub fn isReady(self: PieceAvailability) bool {
return !self.is_downloaded and !self.is_verified and self.available_peers > 0;
}
/// Get selection score for algorithm ranking
pub fn getScore(self: PieceAvailability) i32 {
var score: i32 = 0;
// Priority boost
score += @as(i32, @intCast(@intFromEnum(self.priority))) * 1000;
// Availability boost (rarer pieces get higher score in rarest-first)
score += @as(i32, @intCast(self.available_peers)) * -1;
// Downloaded penalty
if (self.is_downloaded) {
score -= 10000;
}
return score;
}
};
/// Piece selection strategies
pub const SelectionStrategy = enum(u8) {
rarest_first = 1,
random = 2,
sequential = 3,
priority_first = 4,
balanced = 5,
bandwidth_optimized = 6,
network_aware = 7,
};
/// Rate limiting configuration
/// Defaults are read from the centralized core.limits configuration
pub const RateLimit = struct {
max_pieces_per_second: f32 = 10000.0, // Effectively unlimited
max_concurrent_downloads: usize = core.limits.defaults.file.max_concurrent_downloads,
bandwidth_limit_bps: u64 = core.limits.defaults.file.max_bandwidth_download,
pub fn calculateDelay(self: RateLimit, piece_size: usize) f32 {
const bytes_per_second = self.max_pieces_per_second * @as(f32, @floatFromInt(piece_size));
const delay_seconds = @as(f32, @floatFromInt(piece_size)) / bytes_per_second;
return delay_seconds;
}
};
/// Piece selection engine
pub const PieceSelector = struct {
availability_map: std.AutoHashMap(u32, PieceAvailability),
strategy: SelectionStrategy,
rng: std.Random.DefaultPrng,
allocator: mem.Allocator,
rate_limit: RateLimit,
active_downloads: std.AutoHashMap(u32, i64), // piece_index -> start_time
pub fn init(strategy: SelectionStrategy, seed: u64, allocator: mem.Allocator) PieceSelector {
return PieceSelector{
.availability_map = std.AutoHashMap(u32, PieceAvailability).init(allocator),
.strategy = strategy,
.rng = std.Random.DefaultPrng.init(seed),
.allocator = allocator,
.rate_limit = RateLimit{},
.active_downloads = std.AutoHashMap(u32, i64).init(allocator),
};
}
pub fn deinit(self: *PieceSelector) void {
self.availability_map.deinit();
self.active_downloads.deinit();
}
/// Add piece to tracking
pub fn addPiece(self: *PieceSelector, piece_index: u32, available_peers: u32) Error!void {
const entry = PieceAvailability.create(piece_index, available_peers);
try self.availability_map.put(piece_index, entry);
}
/// Update piece availability
pub fn updateAvailability(self: *PieceSelector, piece_index: u32, available_peers: u32) Error!void {
if (self.availability_map.getPtr(piece_index)) |entry| {
entry.available_peers = available_peers;
} else {
// Create new entry if it doesn't exist
try self.addPiece(piece_index, available_peers);
}
}
/// Mark piece as downloaded
pub fn markDownloaded(self: *PieceSelector, piece_index: u32) Error!void {
if (self.availability_map.getPtr(piece_index)) |entry| {
entry.markDownloaded();
}
}
/// Mark piece as pending verification without resetting is_verified
pub fn markPendingVerification(self: *PieceSelector, piece_index: u32) void {
if (self.availability_map.getPtr(piece_index)) |entry| {
entry.markPendingVerification();
}
}
/// Reset downloaded state so piece can be re-requested after verification failure
pub fn resetDownloaded(self: *PieceSelector, piece_index: u32) void {
if (self.availability_map.getPtr(piece_index)) |entry| {
entry.resetDownloaded();
}
}
/// Mark piece as verified
pub fn markVerified(self: *PieceSelector, piece_index: u32) Error!void {
if (self.availability_map.getPtr(piece_index)) |entry| {
entry.markVerified();
}
}
/// Set piece priority
pub fn setPriority(self: *PieceSelector, piece_index: u32, priority: PieceAvailability.Priority) Error!void {
if (self.availability_map.getPtr(piece_index)) |entry| {
entry.setPriority(priority);
}
}
/// Set rate limiting configuration
pub fn setRateLimit(self: *PieceSelector, rate_limit: RateLimit) void {
self.rate_limit = rate_limit;
}
/// Check if we can start a new download (respecting rate limits)
pub fn canStartDownload(self: *PieceSelector, piece_index: u32) bool {
// Check concurrent download limit
if (self.active_downloads.count() >= self.rate_limit.max_concurrent_downloads) {
return false;
}
// Check if already downloading this piece
if (self.active_downloads.contains(piece_index)) {
return false;
}
// Note: Time-based rate limiting removed - it was blocking ALL new downloads
// if ANY active download started within 1 second, effectively limiting to ~1 piece/sec.
// Rate limiting is already handled by max_concurrent_downloads config above.
return true;
}
/// Mark piece as starting download
pub fn startDownload(self: *PieceSelector, piece_index: u32) Error!void {
if (self.canStartDownload(piece_index)) {
try self.active_downloads.put(piece_index, std.time.timestamp());
} else {
return Error.RateLimited;
}
}
/// Mark piece as completed download
pub fn completeDownload(self: *PieceSelector, piece_index: u32) void {
_ = self.active_downloads.remove(piece_index);
}
/// Select next piece to download
/// NOTE: Caller must free returned slice
pub fn selectNext(self: *PieceSelector, max_pieces: ?usize) Error![]u32 {
const pieces = try self.getReadyPieces();
defer self.allocator.free(pieces);
if (pieces.len == 0) {
return &[_]u32{};
}
const selected = switch (self.strategy) {
.rarest_first => try self.selectRarestFirst(pieces),
.random => try self.selectRandom(pieces),
.sequential => try self.selectSequential(pieces),
.priority_first => try self.selectPriorityFirst(pieces),
.balanced => try self.selectBalanced(pieces),
.bandwidth_optimized => try self.selectBandwidthOptimized(pieces),
.network_aware => try self.selectNetworkAware(pieces),
};
// Limit selection if requested
if (max_pieces) |max| {
if (selected.len > max) {
const limited = try self.allocator.alloc(u32, max);
@memcpy(limited, selected[0..max]);
self.allocator.free(selected);
return limited;
}
}
return selected;
}
/// Get all ready pieces
/// NOTE: Caller must free returned slice
fn getReadyPieces(self: *PieceSelector) Error![]u32 {
var ready: std.ArrayList(u32) = .{};
errdefer ready.deinit(self.allocator);
var it = self.availability_map.iterator();
while (it.next()) |entry| {
const piece = entry.value_ptr.*;
if (piece.isReady()) {
ready.append(self.allocator, piece.piece_index) catch return Error.OutOfMemory;
}
}
return ready.toOwnedSlice(self.allocator) catch return Error.OutOfMemory;
}
/// Rarest-first selection
fn selectRarestFirst(self: *PieceSelector, pieces: []const u32) Error![]u32 {
const result = try self.allocator.dupe(u32, pieces);
// Sort by availability (ascending)
mem.sort(u32, result, self, compareByAvailability);
return result;
}
/// Random selection
fn selectRandom(self: *PieceSelector, pieces: []const u32) Error![]u32 {
const result = try self.allocator.dupe(u32, pieces);
// Shuffle pieces randomly
for (result, 0..) |_, i| {
const j = self.rng.random().intRangeLessThan(usize, 0, result.len);
mem.swap(u32, &result[i], &result[j]);
}
return result;
}
/// Sequential selection
fn selectSequential(self: *PieceSelector, pieces: []const u32) Error![]u32 {
const result = try self.allocator.dupe(u32, pieces);
// Sort by piece index (ascending)
mem.sort(u32, result, {}, compareByIndex);
return result;
}
/// Priority-first selection
fn selectPriorityFirst(self: *PieceSelector, pieces: []const u32) Error![]u32 {
const result = try self.allocator.dupe(u32, pieces);
// Sort by priority and score
mem.sort(u32, result, self, compareByPriority);
return result;
}
/// Balanced selection (combination of strategies)
fn selectBalanced(self: *PieceSelector, pieces: []const u32) Error![]u32 {
// Mix of rarest-first and priority
// First prioritize high-priority pieces
// Then use rarest-first for normal priority
var high_priority: std.ArrayList(u32) = .{};
defer high_priority.deinit(self.allocator);
var normal_priority: std.ArrayList(u32) = .{};
defer normal_priority.deinit(self.allocator);
for (pieces) |piece_index| {
if (self.availability_map.get(piece_index)) |piece| {
switch (piece.priority) {
.immediate, .high => high_priority.append(self.allocator, piece_index) catch return Error.OutOfMemory,
else => normal_priority.append(self.allocator, piece_index) catch return Error.OutOfMemory,
}
}
}
// Sort each group
mem.sort(u32, high_priority.items, self, compareByAvailability);
mem.sort(u32, normal_priority.items, self, compareByAvailability);
// Combine results
var combined: std.ArrayList(u32) = .{};
errdefer combined.deinit(self.allocator);
combined.appendSlice(self.allocator, high_priority.items) catch return Error.OutOfMemory;
combined.appendSlice(self.allocator, normal_priority.items) catch return Error.OutOfMemory;
return combined.toOwnedSlice(self.allocator) catch return Error.OutOfMemory;
}
/// Bandwidth-optimized selection (prioritize pieces that maximize throughput)
fn selectBandwidthOptimized(self: *PieceSelector, pieces: []const u32) Error![]u32 {
// Score pieces by availability and estimated bandwidth
var scored_pieces: std.ArrayList(ScoredPiece) = .{};
defer scored_pieces.deinit(self.allocator);
for (pieces) |piece_index| {
if (self.availability_map.get(piece_index)) |piece| {
// Higher score for more available pieces (faster downloads)
const bandwidth_score = @as(f32, @floatFromInt(piece.available_peers)) * 100.0;
// Priority bonus
const priority_score = @as(f32, @floatFromInt(@intFromEnum(piece.priority))) * 10.0;
const total_score = bandwidth_score + priority_score;
scored_pieces.append(self.allocator, ScoredPiece{
.piece_index = piece_index,
.score = total_score,
}) catch return Error.OutOfMemory;
}
}
// Sort by score (highest first)
mem.sort(ScoredPiece, scored_pieces.items, {}, compareScoredPieces);
// Extract piece indices
const result = self.allocator.alloc(u32, scored_pieces.items.len) catch return Error.OutOfMemory;
for (scored_pieces.items, 0..) |scored_piece, i| {
result[i] = scored_piece.piece_index;
}
return result;
}
/// Network-aware selection (considers peer quality and connection stability)
fn selectNetworkAware(self: *PieceSelector, pieces: []const u32) Error![]u32 {
// Mix of rarest-first with network quality considerations
// Prefer pieces from peers with good availability and low latency
var scored_pieces: std.ArrayList(ScoredPiece) = .{};
defer scored_pieces.deinit(self.allocator);
for (pieces) |piece_index| {
if (self.availability_map.get(piece_index)) |piece| {
// Base score from rarity (rarer is better)
const rarity_score = @as(f32, 1000.0) / @as(f32, @floatFromInt(@max(piece.available_peers, 1)));
// Network stability bonus (assume stability correlates with availability)
const stability_score = @as(f32, @floatFromInt(piece.available_peers)) * 5.0;
// Priority bonus
const priority_score = @as(f32, @floatFromInt(@intFromEnum(piece.priority))) * 50.0;
const total_score = rarity_score + stability_score + priority_score;
scored_pieces.append(self.allocator, ScoredPiece{
.piece_index = piece_index,
.score = total_score,
}) catch return Error.OutOfMemory;
}
}
// Sort by score (highest first)
mem.sort(ScoredPiece, scored_pieces.items, {}, compareScoredPieces);
// Extract piece indices
const result = self.allocator.alloc(u32, scored_pieces.items.len) catch return Error.OutOfMemory;
for (scored_pieces.items, 0..) |scored_piece, i| {
result[i] = scored_piece.piece_index;
}
return result;
}
/// Get selection statistics
pub fn getStats(self: *PieceSelector) SelectionStats {
var stats = SelectionStats{};
var it = self.availability_map.iterator();
while (it.next()) |entry| {
const piece = entry.value_ptr.*;
stats.total_pieces += 1;
if (piece.is_downloaded) {
stats.downloaded_pieces += 1;
}
if (piece.is_verified) {
stats.verified_pieces += 1;
}
if (piece.available_peers == 0) {
stats.unavailable_pieces += 1;
}
stats.total_availability += piece.available_peers;
}
return stats;
}
/// Check if all pieces are downloaded
pub fn isComplete(self: *PieceSelector) bool {
var it = self.availability_map.iterator();
while (it.next()) |entry| {
const piece = entry.value_ptr.*;
if (!piece.is_verified) {
return false;
}
}
return true;
}
/// Get download progress (0.0 to 1.0)
pub fn getProgress(self: *PieceSelector) f32 {
const stats = self.getStats();
if (stats.total_pieces == 0) return 0.0;
return @as(f32, @floatFromInt(stats.verified_pieces)) / @as(f32, @floatFromInt(stats.total_pieces));
}
/// Compare function for rarity
fn compareByAvailability(context: *PieceSelector, a: u32, b: u32) bool {
const piece_a = context.availability_map.get(a) orelse PieceAvailability.create(0, 0);
const piece_b = context.availability_map.get(b) orelse PieceAvailability.create(0, 0);
// First by availability (rarer first)
if (piece_a.available_peers != piece_b.available_peers) {
return piece_a.available_peers < piece_b.available_peers;
}
// Then by priority
if (@intFromEnum(piece_a.priority) != @intFromEnum(piece_b.priority)) {
return @intFromEnum(piece_a.priority) > @intFromEnum(piece_b.priority);
}
// Finally by index
return a < b;
}
/// Compare function for priority
fn compareByPriority(context: *PieceSelector, a: u32, b: u32) bool {
const piece_a = context.availability_map.get(a) orelse PieceAvailability.create(0, 0);
const piece_b = context.availability_map.get(b) orelse PieceAvailability.create(0, 0);
// First by priority
if (@intFromEnum(piece_a.priority) != @intFromEnum(piece_b.priority)) {
return @intFromEnum(piece_a.priority) > @intFromEnum(piece_b.priority);
}
// Then by availability
if (piece_a.available_peers != piece_b.available_peers) {
return piece_a.available_peers < piece_b.available_peers;
}
// Finally by index
return a < b;
}
/// Compare function for index
fn compareByIndex(_: void, a: u32, b: u32) bool {
return a < b;
}
};
/// Scored piece for algorithm ranking
const ScoredPiece = struct {
piece_index: u32,
score: f32,
};
/// Compare scored pieces by score (highest first)
fn compareScoredPieces(_: void, a: ScoredPiece, b: ScoredPiece) bool {
return a.score > b.score;
}
/// Selection statistics
pub const SelectionStats = struct {
total_pieces: usize = 0,
downloaded_pieces: usize = 0,
verified_pieces: usize = 0,
unavailable_pieces: usize = 0,
total_availability: u32 = 0,
/// Get download completion percentage
pub fn getCompletionPercent(self: SelectionStats) f32 {
if (self.total_pieces == 0) return 0.0;
return @as(f32, @floatFromInt(self.verified_pieces)) / @as(f32, @floatFromInt(self.total_pieces)) * 100.0;
}
/// Get average availability per piece
pub fn getAverageAvailability(self: SelectionStats) f32 {
if (self.total_pieces == 0) return 0.0;
return @as(f32, @floatFromInt(self.total_availability)) / @as(f32, @floatFromInt(self.total_pieces));
}
};
/// Piece pool for managing piece data
pub const PiecePool = struct {
pieces: std.AutoHashMap(u32, PieceData),
allocator: mem.Allocator,
pub fn init(allocator: mem.Allocator) PiecePool {
return PiecePool{
.pieces = std.AutoHashMap(u32, PieceData).init(allocator),
.allocator = allocator,
};
}
pub fn deinit(self: *PiecePool) void {
var it = self.pieces.valueIterator();
while (it.next()) |piece| {
self.allocator.free(piece.data);
}
self.pieces.deinit();
}
/// Add piece data
pub fn addPiece(self: *PiecePool, piece: PieceData) Error!void {
// Copy piece data to our allocator
const data_copy = self.allocator.alloc(u8, piece.data.len) catch return Error.OutOfMemory;
@memcpy(data_copy, piece.data);
const piece_copy = PieceData{
.index = piece.index,
.data = data_copy,
.hash = piece.hash,
};
try self.pieces.put(piece.index, piece_copy);
}
/// Get piece data
pub fn getPiece(self: *PiecePool, index: u32) ?*PieceData {
return self.pieces.getPtr(index);
}
/// Remove piece data
pub fn removePiece(self: *PiecePool, index: u32) void {
if (self.pieces.fetchRemove(index)) |entry| {
self.allocator.free(entry.value.data);
}
}
/// Check if piece exists
pub fn hasPiece(self: *PiecePool, index: u32) bool {
return self.pieces.contains(index);
}
/// Get all piece indices
/// NOTE: Caller must free returned slice
pub fn getPieceIndices(self: *PiecePool) ![]u32 {
var indices: std.ArrayList(u32) = .{};
errdefer indices.deinit(self.allocator);
var it = self.pieces.keyIterator();
while (it.next()) |index| {
try indices.append(self.allocator, index.*);
}
return indices.toOwnedSlice(self.allocator);
}
/// Get piece count
pub fn count(self: *PiecePool) usize {
return self.pieces.count();
}
/// Clear all pieces
pub fn clear(self: *PiecePool) void {
var it = self.pieces.valueIterator();
while (it.next()) |piece| {
self.allocator.free(piece.data);
}
self.pieces.clearRetainingCapacity();
}
};
/// Piece data structure for storage
pub const PieceData = struct {
index: u32,
data: []u8,
hash: PieceHash,
};
// Testing functions
test "piece availability tracking" {
var availability = PieceAvailability.create(0, 5);
try testing.expectEqual(@as(u32, 0), availability.piece_index);
try testing.expectEqual(@as(u32, 5), availability.available_peers);
try testing.expect(!availability.is_downloaded);
try testing.expect(!availability.is_verified);
try testing.expect(availability.isReady());
// Test marking as downloaded
availability.markDownloaded();
try testing.expect(availability.is_downloaded);
try testing.expect(!availability.is_verified);
try testing.expect(!availability.isReady());
// Test marking as verified
availability.markVerified();
try testing.expect(availability.is_verified);
// Test priority setting
availability.setPriority(.high);
try testing.expectEqual(PieceAvailability.Priority.high, availability.priority);
}
test "piece selector rarest first" {
const allocator = testing.allocator;
const seed: u64 = 12345;
var selector = PieceSelector.init(.rarest_first, seed, allocator);
defer selector.deinit();
// Add pieces with different availability
try selector.addPiece(0, 3); // Common piece
try selector.addPiece(1, 1); // Rare piece
try selector.addPiece(2, 5); // Very common piece
try selector.addPiece(3, 2); // Medium piece
const selected = try selector.selectNext(null);
defer allocator.free(selected);
// Should be sorted by availability (ascending)
try testing.expectEqual(@as(u32, 1), selected[0]); // Rarest (1 peer)
try testing.expectEqual(@as(u32, 3), selected[1]); // Medium (2 peers)
try testing.expectEqual(@as(u32, 0), selected[2]); // Common (3 peers)
try testing.expectEqual(@as(u32, 2), selected[3]); // Most common (5 peers)
}
test "piece selector random" {
const allocator = testing.allocator;
const seed: u64 = 12345;
var selector = PieceSelector.init(.random, seed, allocator);
defer selector.deinit();
// Add pieces
for (0..5) |i| {
try selector.addPiece(@as(u32, @intCast(i)), 3);
}
const selected1 = try selector.selectNext(null);
defer allocator.free(selected1);
// Reset and try again with same seed
var selector2 = PieceSelector.init(.random, seed, allocator);
defer selector2.deinit();
for (0..5) |i| {
try selector2.addPiece(@as(u32, @intCast(i)), 3);
}
const selected2 = try selector2.selectNext(null);
defer allocator.free(selected2);
// Should be in same order due to same seed
try testing.expectEqualSlices(u32, selected1, selected2);
}
test "piece selector sequential" {
const allocator = testing.allocator;
var selector = PieceSelector.init(.sequential, 12345, allocator);
defer selector.deinit();
// Add pieces in random order
try selector.addPiece(3, 2);
try selector.addPiece(1, 3);
try selector.addPiece(4, 1);
try selector.addPiece(0, 4);
try selector.addPiece(2, 5);
const selected = try selector.selectNext(null);
defer allocator.free(selected);
// Should be sorted by index
try testing.expectEqual(@as(u32, 0), selected[0]);
try testing.expectEqual(@as(u32, 1), selected[1]);
try testing.expectEqual(@as(u32, 2), selected[2]);
try testing.expectEqual(@as(u32, 3), selected[3]);
try testing.expectEqual(@as(u32, 4), selected[4]);
}
test "piece selector priority first" {
const allocator = testing.allocator;
var selector = PieceSelector.init(.priority_first, 12345, allocator);
defer selector.deinit();
// Add pieces with different priorities
try selector.addPiece(0, 3);
try selector.setPriority(0, .normal);
try selector.addPiece(1, 3);
try selector.setPriority(1, .high);
try selector.addPiece(2, 3);
try selector.setPriority(2, .low);
try selector.addPiece(3, 3);
try selector.setPriority(3, .immediate);
const selected = try selector.selectNext(null);
defer allocator.free(selected);
// Should be sorted by priority (high to low)
try testing.expectEqual(@as(u32, 3), selected[0]); // immediate
try testing.expectEqual(@as(u32, 1), selected[1]); // high
try testing.expectEqual(@as(u32, 0), selected[2]); // normal
try testing.expectEqual(@as(u32, 2), selected[3]); // low
}
test "piece pool operations" {
const allocator = testing.allocator;
var pool = PiecePool.init(allocator);
defer pool.deinit();
// Create test piece data
var test_data_buf = "Test piece data for pool".*;
const hash = [_]u8{0} ** 32;
const piece = PieceData{
.index = 0,
.data = &test_data_buf,
.hash = hash,
};
// Add piece to pool
try pool.addPiece(piece);
try testing.expect(pool.hasPiece(0));
// Get piece back
const retrieved = pool.getPiece(0);
try testing.expect(retrieved != null);
if (retrieved) |p| {
try testing.expectEqual(@as(u32, 0), p.index);
try testing.expectEqualSlices(u8, &test_data_buf, p.data);
}
// Test piece count
try testing.expectEqual(@as(usize, 1), pool.count());
// Get piece indices
const indices = try pool.getPieceIndices();
defer allocator.free(indices);
try testing.expectEqual(@as(usize, 1), indices.len);
try testing.expectEqual(@as(u32, 0), indices[0]);
// Remove piece
pool.removePiece(0);
try testing.expect(!pool.hasPiece(0));
try testing.expectEqual(@as(usize, 0), pool.count());
}
test "selection statistics" {
const allocator = testing.allocator;
var selector = PieceSelector.init(.rarest_first, 12345, allocator);
defer selector.deinit();
// Add various pieces
try selector.addPiece(0, 2); // Normal
try selector.addPiece(1, 0); // Unavailable
try selector.addPiece(2, 1); // Downloaded/verified piece
try selector.markDownloaded(2);
try selector.markVerified(2);
try selector.addPiece(3, 5); // Common
const stats = selector.getStats();
try testing.expectEqual(@as(usize, 4), stats.total_pieces);
try testing.expectEqual(@as(usize, 1), stats.downloaded_pieces);
try testing.expectEqual(@as(usize, 1), stats.verified_pieces);
try testing.expectEqual(@as(usize, 1), stats.unavailable_pieces);
// Test progress calculation (1 downloaded out of 4)
const progress = selector.getProgress();
try testing.expectEqual(@as(f32, 1.0 / 4.0), progress);
// Test completion
try testing.expect(!selector.isComplete());
}
test "piece selector max pieces limit" {
const allocator = testing.allocator;
var selector = PieceSelector.init(.sequential, 12345, allocator);
defer selector.deinit();
// Add many pieces
for (0..10) |i| {
try selector.addPiece(@as(u32, @intCast(i)), 1);
}
// Limit selection to 3 pieces
const selected = try selector.selectNext(3);
defer allocator.free(selected);
try testing.expectEqual(@as(usize, 3), selected.len);
try testing.expectEqual(@as(u32, 0), selected[0]);
try testing.expectEqual(@as(u32, 1), selected[1]);
try testing.expectEqual(@as(u32, 2), selected[2]);
}

View File

@@ -0,0 +1,365 @@
//! Pre-allocated Buffer Pool for Piece Data
//!
//! Provides a thread-safe pool of pre-allocated buffers for piece processing,
//! reducing allocation overhead during high-throughput file transfers.
//!
//! PERF: This addresses memory allocation overhead in piece verification and
//! disk I/O operations by reusing buffers instead of allocating new ones.
const std = @import("std");
const atomic = std.atomic;
const mem = std.mem;
const core = @import("core");
const Error = core.errors.Error;
/// Configuration for the piece buffer pool
pub const PieceBufferPoolConfig = struct {
/// Size of each buffer (should match piece_size)
buffer_size: usize = 1024 * 1024, // 1MB default
/// Number of buffers to pre-allocate
num_buffers: usize = 128,
/// Whether to allow fallback to regular allocation when pool is exhausted
allow_fallback: bool = true,
};
/// A pooled buffer that must be returned to the pool when done
pub const PooledBuffer = struct {
/// The actual buffer data
data: []u8,
/// Index in the pool (NO_INDEX if fallback allocation)
pool_index: usize,
/// Reference to the pool for returning
pool: *PieceBufferPool,
/// Actual used length (may be less than data.len)
len: usize,
const NO_INDEX = std.math.maxInt(usize);
/// Get the used portion of the buffer
pub fn slice(self: *const PooledBuffer) []u8 {
return self.data[0..self.len];
}
/// Return this buffer to the pool
pub fn release(self: *PooledBuffer) void {
self.pool.releaseBuffer(self);
}
};
/// Thread-safe pool of pre-allocated piece buffers
pub const PieceBufferPool = struct {
allocator: mem.Allocator,
config: PieceBufferPoolConfig,
/// Pre-allocated buffer storage
buffers: [][]u8,
/// Free list using indices (thread-safe via mutex)
free_stack: std.ArrayList(usize),
mutex: std.Thread.Mutex,
/// Statistics
acquired_count: atomic.Value(u64),
released_count: atomic.Value(u64),
fallback_count: atomic.Value(u64),
pool_hits: atomic.Value(u64),
pool_misses: atomic.Value(u64),
pub fn init(allocator: mem.Allocator, config: PieceBufferPoolConfig) Error!PieceBufferPool {
// Allocate buffer pointer array
const buffers = allocator.alloc([]u8, config.num_buffers) catch {
return Error.OutOfMemory;
};
errdefer allocator.free(buffers);
// Pre-allocate all buffers
var allocated: usize = 0;
errdefer {
for (buffers[0..allocated]) |buf| {
allocator.free(buf);
}
}
for (buffers) |*buf| {
buf.* = allocator.alloc(u8, config.buffer_size) catch {
return Error.OutOfMemory;
};
allocated += 1;
}
// Initialize free stack with all buffer indices
var free_stack = std.ArrayList(usize){};
free_stack.ensureTotalCapacity(allocator, config.num_buffers) catch {
return Error.OutOfMemory;
};
// Add all indices to free stack (in reverse order so index 0 is at top)
var i: usize = config.num_buffers;
while (i > 0) {
i -= 1;
free_stack.appendAssumeCapacity(i);
}
return .{
.allocator = allocator,
.config = config,
.buffers = buffers,
.free_stack = free_stack,
.mutex = .{},
.acquired_count = atomic.Value(u64).init(0),
.released_count = atomic.Value(u64).init(0),
.fallback_count = atomic.Value(u64).init(0),
.pool_hits = atomic.Value(u64).init(0),
.pool_misses = atomic.Value(u64).init(0),
};
}
pub fn deinit(self: *PieceBufferPool) void {
// Free all pre-allocated buffers
for (self.buffers) |buf| {
self.allocator.free(buf);
}
self.allocator.free(self.buffers);
self.free_stack.deinit(self.allocator);
}
/// Acquire a buffer from the pool
/// If pool is exhausted and allow_fallback is true, allocates from heap
/// Returns null if pool exhausted and fallback disabled
pub fn acquire(self: *PieceBufferPool, required_size: usize) ?PooledBuffer {
// Check size fits in pool buffers
if (required_size > self.config.buffer_size) {
if (self.config.allow_fallback) {
return self.allocateFallback(required_size);
}
return null;
}
// Try to get from pool
self.mutex.lock();
const maybe_index: ?usize = if (self.free_stack.items.len > 0)
self.free_stack.pop()
else
null;
self.mutex.unlock();
if (maybe_index) |index| {
_ = self.acquired_count.fetchAdd(1, .monotonic);
_ = self.pool_hits.fetchAdd(1, .monotonic);
return PooledBuffer{
.data = self.buffers[index],
.pool_index = index,
.pool = self,
.len = required_size,
};
}
// Pool exhausted
_ = self.pool_misses.fetchAdd(1, .monotonic);
if (self.config.allow_fallback) {
return self.allocateFallback(required_size);
}
return null;
}
/// Acquire a buffer and copy data into it
pub fn acquireWithData(self: *PieceBufferPool, data: []const u8) ?PooledBuffer {
var buffer = self.acquire(data.len) orelse return null;
@memcpy(buffer.data[0..data.len], data);
buffer.len = data.len;
return buffer;
}
/// Release a buffer back to the pool
pub fn releaseBuffer(self: *PieceBufferPool, buffer: *PooledBuffer) void {
_ = self.released_count.fetchAdd(1, .monotonic);
if (buffer.pool_index == PooledBuffer.NO_INDEX) {
// Fallback allocation - free it
self.allocator.free(buffer.data);
return;
}
// Return to pool
self.mutex.lock();
defer self.mutex.unlock();
// Push index back onto free stack
self.free_stack.append(self.allocator, buffer.pool_index) catch {
// Should never fail since we pre-allocated capacity
// But if it does, the buffer is leaked (not catastrophic)
std.log.err("PieceBufferPool: Failed to return buffer to pool", .{});
};
}
fn allocateFallback(self: *PieceBufferPool, size: usize) ?PooledBuffer {
const data = self.allocator.alloc(u8, size) catch return null;
_ = self.fallback_count.fetchAdd(1, .monotonic);
_ = self.acquired_count.fetchAdd(1, .monotonic);
return PooledBuffer{
.data = data,
.pool_index = PooledBuffer.NO_INDEX,
.pool = self,
.len = size,
};
}
/// Get pool statistics
pub fn getStats(self: *const PieceBufferPool) PieceBufferPoolStats {
// Cast away const for mutex (stats don't modify logical state)
const self_mut = @constCast(self);
self_mut.mutex.lock();
defer self_mut.mutex.unlock();
return .{
.total_buffers = self.config.num_buffers,
.available_buffers = self.free_stack.items.len,
.in_use_buffers = self.config.num_buffers - self.free_stack.items.len,
.buffer_size = self.config.buffer_size,
.acquired_count = self.acquired_count.load(.acquire),
.released_count = self.released_count.load(.acquire),
.fallback_count = self.fallback_count.load(.acquire),
.pool_hits = self.pool_hits.load(.acquire),
.pool_misses = self.pool_misses.load(.acquire),
};
}
};
/// Statistics for the piece buffer pool
pub const PieceBufferPoolStats = struct {
total_buffers: usize,
available_buffers: usize,
in_use_buffers: usize,
buffer_size: usize,
acquired_count: u64,
released_count: u64,
fallback_count: u64,
pool_hits: u64,
pool_misses: u64,
pub fn hitRate(self: *const PieceBufferPoolStats) f32 {
const total = self.pool_hits + self.pool_misses;
if (total == 0) return 1.0;
return @as(f32, @floatFromInt(self.pool_hits)) / @as(f32, @floatFromInt(total));
}
pub fn utilizationRate(self: *const PieceBufferPoolStats) f32 {
if (self.total_buffers == 0) return 0.0;
return @as(f32, @floatFromInt(self.in_use_buffers)) / @as(f32, @floatFromInt(self.total_buffers));
}
};
// Tests
test "piece buffer pool basic operations" {
const allocator = std.testing.allocator;
var pool = try PieceBufferPool.init(allocator, .{
.buffer_size = 1024,
.num_buffers = 4,
.allow_fallback = false,
});
defer pool.deinit();
// Acquire all buffers
var buffers: [4]PooledBuffer = undefined;
for (&buffers) |*buf| {
buf.* = pool.acquire(512) orelse unreachable;
}
// Pool should be exhausted
try std.testing.expect(pool.acquire(512) == null);
// Release one
buffers[0].release();
// Should be able to acquire again
var new_buf = pool.acquire(512) orelse unreachable;
new_buf.release();
// Release remaining
for (buffers[1..]) |*buf| {
var buf_mut = buf.*;
buf_mut.release();
}
const stats = pool.getStats();
try std.testing.expectEqual(@as(usize, 4), stats.available_buffers);
}
test "piece buffer pool with data copy" {
const allocator = std.testing.allocator;
var pool = try PieceBufferPool.init(allocator, .{
.buffer_size = 1024,
.num_buffers = 2,
});
defer pool.deinit();
const test_data = "Hello, World! This is test data for the buffer pool.";
var buffer = pool.acquireWithData(test_data) orelse unreachable;
defer buffer.release();
try std.testing.expectEqualSlices(u8, test_data, buffer.slice());
}
test "piece buffer pool fallback allocation" {
const allocator = std.testing.allocator;
var pool = try PieceBufferPool.init(allocator, .{
.buffer_size = 1024,
.num_buffers = 1,
.allow_fallback = true,
});
defer pool.deinit();
// Acquire from pool
var buf1 = pool.acquire(512) orelse unreachable;
// Should fallback to heap
var buf2 = pool.acquire(512) orelse unreachable;
// Also test oversized request (always fallback)
var buf3 = pool.acquire(2048) orelse unreachable;
const stats = pool.getStats();
try std.testing.expectEqual(@as(u64, 2), stats.fallback_count);
buf3.release();
buf2.release();
buf1.release();
}
test "piece buffer pool statistics" {
const allocator = std.testing.allocator;
var pool = try PieceBufferPool.init(allocator, .{
.buffer_size = 1024,
.num_buffers = 4,
});
defer pool.deinit();
// Initial stats
var stats = pool.getStats();
try std.testing.expectEqual(@as(usize, 4), stats.total_buffers);
try std.testing.expectEqual(@as(usize, 4), stats.available_buffers);
try std.testing.expectEqual(@as(usize, 0), stats.in_use_buffers);
// Acquire some
var buf1 = pool.acquire(512) orelse unreachable;
var buf2 = pool.acquire(512) orelse unreachable;
stats = pool.getStats();
try std.testing.expectEqual(@as(usize, 2), stats.in_use_buffers);
try std.testing.expectEqual(@as(u64, 2), stats.acquired_count);
try std.testing.expectEqual(@as(u64, 2), stats.pool_hits);
buf1.release();
buf2.release();
stats = pool.getStats();
try std.testing.expectEqual(@as(u64, 2), stats.released_count);
}

View File

@@ -0,0 +1,461 @@
//! Multi-threaded Piece Processing Pipeline
//!
//! Provides a parallel pipeline for piece processing, allowing the network thread
//! to quickly queue incoming pieces while worker threads handle validation,
//! disk writes, and verification in parallel.
//!
//! PERF: This addresses the bottleneck where piece processing is sequential,
//! even though individual operations (pwrite, SHA-256) are optimized.
//!
//! Pipeline Architecture:
//! ```
//! Network Thread Worker Threads (N)
//! | |
//! v v
//! [Queue Piece] -----> [Task Queue] ----> [Process]
//! | |
//! v +-> Validate
//! (returns +-> Disk Write (pwrite)
//! immediately) +-> Queue Verification
//! +-> Update State
//! ```
const std = @import("std");
const atomic = std.atomic;
const mem = std.mem;
const Thread = std.Thread;
const core = @import("core");
const Error = core.errors.Error;
const file_mod = @import("file.zig");
/// Configuration for the piece pipeline
pub const PiecePipelineConfig = struct {
/// Number of worker threads (0 = auto-detect based on CPU count)
num_workers: u32 = 0,
/// Maximum pending tasks in the queue
max_queue_size: usize = 2048,
/// Whether to use high-priority processing for small pieces
prioritize_small_pieces: bool = true,
};
/// A piece task to be processed by the pipeline
pub const PieceTask = struct {
/// Peer ID that sent this piece
peer_id: [32]u8,
/// Content hash for session lookup
content_hash: [32]u8,
/// Piece index
piece_index: u32,
/// Offset within the piece
offset: u32,
/// Piece data (owned copy)
data: []u8,
/// Allocator used for data
allocator: mem.Allocator,
/// Timestamp when queued (nanoseconds)
queued_at: i128,
pub fn deinit(self: *PieceTask) void {
self.allocator.free(self.data);
}
};
/// Callback interface for pipeline events
pub const PipelineCallbacks = struct {
/// Context pointer passed to callbacks
context: *anyopaque,
/// Called to process a piece (validation, disk write, verification queueing)
/// Returns true if piece was processed successfully
process_piece_fn: *const fn (
ctx: *anyopaque,
peer_id: [32]u8,
content_hash: [32]u8,
piece_index: u32,
offset: u32,
data: []const u8,
) Error!void,
pub fn processPiece(
self: *const PipelineCallbacks,
peer_id: [32]u8,
content_hash: [32]u8,
piece_index: u32,
offset: u32,
data: []const u8,
) Error!void {
return self.process_piece_fn(self.context, peer_id, content_hash, piece_index, offset, data);
}
};
/// Multi-threaded piece processing pipeline
pub const PiecePipeline = struct {
allocator: mem.Allocator,
config: PiecePipelineConfig,
/// Task queue
task_queue: std.ArrayList(PieceTask),
queue_mutex: Thread.Mutex,
queue_not_empty: Thread.Condition,
/// Worker threads
workers: std.ArrayList(Thread),
/// Shutdown flag
shutdown: atomic.Value(bool),
/// Callbacks for piece processing
callbacks: ?PipelineCallbacks,
/// Statistics
tasks_queued: atomic.Value(u64),
tasks_processed: atomic.Value(u64),
tasks_failed: atomic.Value(u64),
queue_full_count: atomic.Value(u64),
total_queue_wait_ns: atomic.Value(u64),
pub fn init(allocator: mem.Allocator, config: PiecePipelineConfig) PiecePipeline {
return .{
.allocator = allocator,
.config = config,
.task_queue = .{},
.queue_mutex = .{},
.queue_not_empty = .{},
.workers = .{},
.shutdown = atomic.Value(bool).init(false),
.callbacks = null,
.tasks_queued = atomic.Value(u64).init(0),
.tasks_processed = atomic.Value(u64).init(0),
.tasks_failed = atomic.Value(u64).init(0),
.queue_full_count = atomic.Value(u64).init(0),
.total_queue_wait_ns = atomic.Value(u64).init(0),
};
}
pub fn deinit(self: *PiecePipeline) void {
self.stop();
// Clean up any remaining tasks
for (self.task_queue.items) |*task| {
task.deinit();
}
self.task_queue.deinit(self.allocator);
self.workers.deinit(self.allocator);
}
/// Set the callbacks for piece processing
pub fn setCallbacks(self: *PiecePipeline, callbacks: PipelineCallbacks) void {
self.callbacks = callbacks;
}
/// Start worker threads
pub fn start(self: *PiecePipeline) Error!void {
if (self.callbacks == null) {
return Error.InvalidState;
}
const num_workers = if (self.config.num_workers == 0)
@as(u32, @intCast(@max(1, Thread.getCpuCount() catch 4)))
else
self.config.num_workers;
var i: u32 = 0;
while (i < num_workers) : (i += 1) {
const thread = Thread.spawn(.{}, workerLoop, .{self}) catch {
return Error.InvalidState;
};
self.workers.append(self.allocator, thread) catch {
return Error.OutOfMemory;
};
}
}
/// Stop all worker threads
pub fn stop(self: *PiecePipeline) void {
self.shutdown.store(true, .release);
// Wake up all workers
self.queue_mutex.lock();
self.queue_not_empty.broadcast();
self.queue_mutex.unlock();
// Wait for workers to finish
for (self.workers.items) |worker| {
worker.join();
}
self.workers.clearRetainingCapacity();
}
/// Queue a piece for processing (non-blocking for caller)
/// The data is COPIED - caller can free their copy after this returns
pub fn queuePiece(
self: *PiecePipeline,
peer_id: [32]u8,
content_hash: [32]u8,
piece_index: u32,
offset: u32,
data: []const u8,
) Error!void {
// Copy data since original payload will be freed
const data_copy = self.allocator.alloc(u8, data.len) catch {
return Error.OutOfMemory;
};
errdefer self.allocator.free(data_copy);
@memcpy(data_copy, data);
self.queue_mutex.lock();
defer self.queue_mutex.unlock();
// Check queue size
if (self.task_queue.items.len >= self.config.max_queue_size) {
// data_copy freed by errdefer above on error return
_ = self.queue_full_count.fetchAdd(1, .monotonic);
return Error.QueueFull;
}
// Add to queue
self.task_queue.append(self.allocator, .{
.peer_id = peer_id,
.content_hash = content_hash,
.piece_index = piece_index,
.offset = offset,
.data = data_copy,
.allocator = self.allocator,
.queued_at = std.time.nanoTimestamp(),
}) catch {
self.allocator.free(data_copy);
return Error.OutOfMemory;
};
_ = self.tasks_queued.fetchAdd(1, .monotonic);
self.queue_not_empty.signal();
}
/// Get current queue depth
pub fn getQueueDepth(self: *PiecePipeline) usize {
self.queue_mutex.lock();
defer self.queue_mutex.unlock();
return self.task_queue.items.len;
}
/// Get pipeline statistics
pub fn getStats(self: *const PiecePipeline) PipelineStats {
const self_mut = @constCast(self);
self_mut.queue_mutex.lock();
defer self_mut.queue_mutex.unlock();
const processed = self.tasks_processed.load(.acquire);
const total_wait = self.total_queue_wait_ns.load(.acquire);
return .{
.tasks_queued = self.tasks_queued.load(.acquire),
.tasks_processed = processed,
.tasks_failed = self.tasks_failed.load(.acquire),
.queue_full_count = self.queue_full_count.load(.acquire),
.current_queue_depth = self.task_queue.items.len,
.worker_count = self.workers.items.len,
.avg_queue_wait_ns = if (processed > 0) total_wait / processed else 0,
};
}
/// Worker thread loop
fn workerLoop(self: *PiecePipeline) void {
while (!self.shutdown.load(.acquire)) {
// Get next task
var task: ?PieceTask = null;
{
self.queue_mutex.lock();
defer self.queue_mutex.unlock();
while (self.task_queue.items.len == 0 and !self.shutdown.load(.acquire)) {
self.queue_not_empty.wait(&self.queue_mutex);
}
if (self.shutdown.load(.acquire) and self.task_queue.items.len == 0) {
break;
}
if (self.task_queue.items.len > 0) {
task = self.task_queue.orderedRemove(0);
}
}
// Process task outside lock
if (task) |*t| {
defer t.deinit();
// Track queue wait time
const wait_ns: u64 = @intCast(@max(0, std.time.nanoTimestamp() - t.queued_at));
_ = self.total_queue_wait_ns.fetchAdd(wait_ns, .monotonic);
// Process the piece via callback
if (self.callbacks) |cb| {
cb.processPiece(
t.peer_id,
t.content_hash,
t.piece_index,
t.offset,
t.data,
) catch |err| {
std.log.warn("PIPELINE: piece {} processing failed: {}", .{ t.piece_index, err });
_ = self.tasks_failed.fetchAdd(1, .monotonic);
continue;
};
}
_ = self.tasks_processed.fetchAdd(1, .monotonic);
}
}
// Drain remaining tasks on shutdown
while (true) {
self.queue_mutex.lock();
const maybe_task = if (self.task_queue.items.len > 0)
self.task_queue.orderedRemove(0)
else
null;
self.queue_mutex.unlock();
if (maybe_task) |*t| {
var task = t.*;
defer task.deinit();
if (self.callbacks) |cb| {
cb.processPiece(
task.peer_id,
task.content_hash,
task.piece_index,
task.offset,
task.data,
) catch {
_ = self.tasks_failed.fetchAdd(1, .monotonic);
continue;
};
}
_ = self.tasks_processed.fetchAdd(1, .monotonic);
} else {
break;
}
}
}
};
/// Pipeline statistics
pub const PipelineStats = struct {
tasks_queued: u64,
tasks_processed: u64,
tasks_failed: u64,
queue_full_count: u64,
current_queue_depth: usize,
worker_count: usize,
avg_queue_wait_ns: u64,
pub fn throughput(self: *const PipelineStats, elapsed_secs: f64) f64 {
if (elapsed_secs <= 0) return 0;
return @as(f64, @floatFromInt(self.tasks_processed)) / elapsed_secs;
}
};
// Tests
test "piece pipeline basic operations" {
const allocator = std.testing.allocator;
const TestContext = struct {
processed_count: u32 = 0,
mutex: Thread.Mutex = .{},
};
var ctx = TestContext{};
const TestCallbacks = struct {
fn process(
raw_ctx: *anyopaque,
_: [32]u8,
_: [32]u8,
_: u32,
_: u32,
_: []const u8,
) Error!void {
const self: *TestContext = @ptrCast(@alignCast(raw_ctx));
self.mutex.lock();
defer self.mutex.unlock();
self.processed_count += 1;
}
};
var pipeline = PiecePipeline.init(allocator, .{ .num_workers = 2 });
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&ctx),
.process_piece_fn = TestCallbacks.process,
});
try pipeline.start();
// Queue some pieces
const test_data = "Test piece data";
const test_hash = [_]u8{0x01} ** 32;
const test_peer = [_]u8{0x02} ** 32;
var i: u32 = 0;
while (i < 10) : (i += 1) {
try pipeline.queuePiece(test_peer, test_hash, i, 0, test_data);
}
// Wait for processing
var attempts: u32 = 0;
while (attempts < 100) : (attempts += 1) {
ctx.mutex.lock();
const count = ctx.processed_count;
ctx.mutex.unlock();
if (count >= 10) break;
std.Thread.sleep(10 * std.time.ns_per_ms);
}
pipeline.stop();
const stats = pipeline.getStats();
try std.testing.expectEqual(@as(u64, 10), stats.tasks_queued);
}
test "piece pipeline queue full handling" {
const allocator = std.testing.allocator;
const DummyCallbacks = struct {
fn process(_: *anyopaque, _: [32]u8, _: [32]u8, _: u32, _: u32, _: []const u8) Error!void {}
};
var dummy: u32 = 0;
var pipeline = PiecePipeline.init(allocator, .{
.num_workers = 1,
.max_queue_size = 2,
});
defer pipeline.deinit();
pipeline.setCallbacks(.{
.context = @ptrCast(&dummy),
.process_piece_fn = DummyCallbacks.process,
});
// Queue items BEFORE starting workers so nothing is consumed
const test_data = "Test";
const test_hash = [_]u8{0x01} ** 32;
const test_peer = [_]u8{0x02} ** 32;
// Fill queue to capacity
try pipeline.queuePiece(test_peer, test_hash, 0, 0, test_data);
try pipeline.queuePiece(test_peer, test_hash, 1, 0, test_data);
// This should fail with QueueFull
const result = pipeline.queuePiece(test_peer, test_hash, 2, 0, test_data);
try std.testing.expectError(Error.QueueFull, result);
const stats = pipeline.getStats();
try std.testing.expectEqual(@as(u64, 1), stats.queue_full_count);
// Start and stop to drain the queue cleanly
try pipeline.start();
pipeline.stop();
}

3397
src/files/transfer.zig Normal file

File diff suppressed because it is too large Load Diff

1652
src/files/upload.zig Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,434 @@
//! Parallel SHA-256 Verification Pool
//!
//! Provides a thread pool for parallel piece verification, improving throughput
//! when downloading from multiple peers by offloading CPU-intensive SHA-256
//! computation to worker threads.
//!
//! PERF: This addresses the bottleneck where single-threaded verification
//! limits multi-peer download throughput.
const std = @import("std");
const atomic = std.atomic;
const mem = std.mem;
const core = @import("core");
const Error = core.errors.Error;
const hash_mod = @import("hash.zig");
const HashUtils = hash_mod.HashUtils;
const PieceHash = hash_mod.PieceHash;
const piece_buffer_pool = @import("piece_buffer_pool.zig");
const PieceBufferPool = piece_buffer_pool.PieceBufferPool;
const PooledBuffer = piece_buffer_pool.PooledBuffer;
/// Storage type for task data - either pooled or heap-allocated
pub const TaskStorage = union(enum) {
/// Buffer from pool (preferred - less allocation overhead)
pooled: PooledBuffer,
/// Heap-allocated fallback
heap: struct {
data: []u8,
allocator: mem.Allocator,
},
pub fn getData(self: *TaskStorage) []u8 {
return switch (self.*) {
.pooled => |*pb| pb.slice(),
.heap => |h| h.data,
};
}
pub fn release(self: *TaskStorage) void {
switch (self.*) {
.pooled => |*pb| pb.release(),
.heap => |h| h.allocator.free(h.data),
}
}
};
/// Verification task to be processed by worker threads
pub const VerificationTask = struct {
/// Session ID for callback routing
session_id: u64,
/// Piece index being verified
piece_index: u32,
/// Data storage (pooled or heap)
storage: TaskStorage,
/// Expected SHA-256 hash
expected_hash: PieceHash,
/// Peer ID for reputation update
peer_id: [32]u8,
pub fn getData(self: *VerificationTask) []u8 {
return self.storage.getData();
}
pub fn deinit(self: *VerificationTask) void {
self.storage.release();
}
};
/// Result of a verification task
pub const VerificationResult = struct {
session_id: u64,
piece_index: u32,
is_valid: bool,
completed_at: i64,
peer_id: [32]u8,
};
/// Configuration for the verification pool
pub const VerificationPoolConfig = struct {
/// Number of worker threads (0 = auto-detect based on CPU count)
num_workers: u32 = 0,
/// Maximum pending tasks before blocking
max_pending_tasks: usize = 1024,
/// Whether to use results queue (alternative to callbacks)
use_results_queue: bool = true,
/// PERF: Number of pre-allocated buffers for piece data (0 = disabled)
num_piece_buffers: usize = 128,
/// PERF: Size of each pre-allocated buffer (should match piece_size)
piece_buffer_size: usize = 1024 * 1024, // 1MB default
};
/// Thread pool for parallel SHA-256 verification
pub const VerificationPool = struct {
allocator: mem.Allocator,
config: VerificationPoolConfig,
/// Task queue for pending verifications
task_queue: std.ArrayList(VerificationTask),
task_mutex: std.Thread.Mutex,
/// Condition variable for worker wakeup
task_condition: std.Thread.Condition,
/// Results queue (if use_results_queue is true)
results_queue: std.ArrayList(VerificationResult),
results_mutex: std.Thread.Mutex,
/// Worker threads
workers: std.ArrayList(std.Thread),
/// Shutdown flag
shutdown: atomic.Value(bool),
/// PERF: Pre-allocated buffer pool for piece data
buffer_pool: ?*PieceBufferPool,
/// Statistics
tasks_completed: atomic.Value(u64),
tasks_failed: atomic.Value(u64),
total_bytes_verified: atomic.Value(u64),
pool_hits: atomic.Value(u64),
pool_misses: atomic.Value(u64),
pub fn init(allocator: mem.Allocator, config: VerificationPoolConfig) Error!VerificationPool {
// Initialize buffer pool if configured
var buffer_pool: ?*PieceBufferPool = null;
if (config.num_piece_buffers > 0) {
const pool_ptr = allocator.create(PieceBufferPool) catch {
return Error.OutOfMemory;
};
errdefer allocator.destroy(pool_ptr);
pool_ptr.* = PieceBufferPool.init(allocator, .{
.buffer_size = config.piece_buffer_size,
.num_buffers = config.num_piece_buffers,
.allow_fallback = true, // Allow heap fallback when pool exhausted
}) catch {
// errdefer will handle destroy
return Error.OutOfMemory;
};
buffer_pool = pool_ptr;
}
return .{
.allocator = allocator,
.config = config,
.task_queue = .{},
.task_mutex = .{},
.task_condition = .{},
.results_queue = .{},
.results_mutex = .{},
.workers = .{},
.shutdown = atomic.Value(bool).init(false),
.buffer_pool = buffer_pool,
.tasks_completed = atomic.Value(u64).init(0),
.tasks_failed = atomic.Value(u64).init(0),
.total_bytes_verified = atomic.Value(u64).init(0),
.pool_hits = atomic.Value(u64).init(0),
.pool_misses = atomic.Value(u64).init(0),
};
}
pub fn deinit(self: *VerificationPool) void {
self.stop();
// Clean up any pending tasks (release their buffers)
for (self.task_queue.items) |*task| {
task.deinit();
}
self.task_queue.deinit(self.allocator);
self.results_queue.deinit(self.allocator);
self.workers.deinit(self.allocator);
// Clean up buffer pool
if (self.buffer_pool) |pool| {
pool.deinit();
self.allocator.destroy(pool);
}
}
/// Start worker threads
pub fn start(self: *VerificationPool) Error!void {
const num_workers = if (self.config.num_workers == 0)
@as(u32, @intCast(@max(1, std.Thread.getCpuCount() catch 4)))
else
self.config.num_workers;
var i: u32 = 0;
while (i < num_workers) : (i += 1) {
const thread = std.Thread.spawn(.{}, workerLoop, .{self}) catch {
return Error.InvalidState;
};
self.workers.append(self.allocator, thread) catch {
return Error.OutOfMemory;
};
}
}
/// Stop all worker threads
pub fn stop(self: *VerificationPool) void {
self.shutdown.store(true, .release);
// Wake up all workers
self.task_mutex.lock();
self.task_condition.broadcast();
self.task_mutex.unlock();
// Wait for workers to finish
for (self.workers.items) |worker| {
worker.join();
}
self.workers.clearRetainingCapacity();
}
/// Queue a piece for verification
/// The data is COPIED - caller can free their copy after this returns
/// Returns error if queue is full or allocation fails
pub fn queueVerification(
self: *VerificationPool,
session_id: u64,
piece_index: u32,
data: []const u8,
expected_hash: PieceHash,
peer_id: [32]u8,
) Error!void {
// PERF: Try to get buffer from pool first, fallback to heap allocation
var storage: TaskStorage = undefined;
if (self.buffer_pool) |pool| {
if (pool.acquireWithData(data)) |pooled_buf| {
storage = .{ .pooled = pooled_buf };
_ = self.pool_hits.fetchAdd(1, .monotonic);
} else {
// Pool exhausted - fallback to heap (pool's allow_fallback handles this,
// but if it's disabled we need manual fallback)
_ = self.pool_misses.fetchAdd(1, .monotonic);
const data_copy = self.allocator.alloc(u8, data.len) catch {
return Error.OutOfMemory;
};
@memcpy(data_copy, data);
storage = .{ .heap = .{ .data = data_copy, .allocator = self.allocator } };
}
} else {
// No buffer pool - use heap allocation
const data_copy = self.allocator.alloc(u8, data.len) catch {
return Error.OutOfMemory;
};
@memcpy(data_copy, data);
storage = .{ .heap = .{ .data = data_copy, .allocator = self.allocator } };
}
errdefer storage.release();
self.task_mutex.lock();
defer self.task_mutex.unlock();
if (self.task_queue.items.len >= self.config.max_pending_tasks) {
// errdefer will handle storage.release() on error return
return Error.QueueFull;
}
// errdefer will handle storage.release() if append fails
self.task_queue.append(self.allocator, .{
.session_id = session_id,
.piece_index = piece_index,
.storage = storage,
.expected_hash = expected_hash,
.peer_id = peer_id,
}) catch return Error.OutOfMemory;
self.task_condition.signal();
}
/// Get next completed result (non-blocking)
/// Returns null if no results available
pub fn getResult(self: *VerificationPool) ?VerificationResult {
self.results_mutex.lock();
defer self.results_mutex.unlock();
if (self.results_queue.items.len > 0) {
return self.results_queue.orderedRemove(0);
}
return null;
}
/// Get number of pending tasks
pub fn getPendingCount(self: *VerificationPool) usize {
self.task_mutex.lock();
defer self.task_mutex.unlock();
return self.task_queue.items.len;
}
/// Get statistics
pub fn getStats(self: *VerificationPool) struct {
completed: u64,
failed: u64,
bytes_verified: u64,
pending: usize,
} {
return .{
.completed = self.tasks_completed.load(.acquire),
.failed = self.tasks_failed.load(.acquire),
.bytes_verified = self.total_bytes_verified.load(.acquire),
.pending = self.getPendingCount(),
};
}
/// Worker thread loop
fn workerLoop(self: *VerificationPool) void {
while (!self.shutdown.load(.acquire)) {
// Get next task
var task: ?VerificationTask = null;
{
self.task_mutex.lock();
defer self.task_mutex.unlock();
while (self.task_queue.items.len == 0 and !self.shutdown.load(.acquire)) {
self.task_condition.wait(&self.task_mutex);
}
if (self.shutdown.load(.acquire)) {
break;
}
if (self.task_queue.items.len > 0) {
task = self.task_queue.orderedRemove(0);
}
}
// Process task outside lock
if (task) |*t| {
const task_data = t.getData();
const is_valid = HashUtils.verify(task_data, t.expected_hash) catch false;
const data_len = task_data.len;
const peer_id = t.peer_id;
// Release the buffer (back to pool or free heap memory)
t.deinit();
// Update statistics
_ = self.tasks_completed.fetchAdd(1, .release);
_ = self.total_bytes_verified.fetchAdd(data_len, .release);
if (!is_valid) {
_ = self.tasks_failed.fetchAdd(1, .release);
}
// Add to results queue if enabled
if (self.config.use_results_queue) {
self.results_mutex.lock();
defer self.results_mutex.unlock();
self.results_queue.append(self.allocator, .{
.session_id = t.session_id,
.piece_index = t.piece_index,
.is_valid = is_valid,
.completed_at = std.time.milliTimestamp(),
.peer_id = peer_id,
}) catch |err| {
std.log.err("Failed to queue verification result for piece {}: {} - result lost", .{ t.piece_index, err });
};
}
}
}
}
};
// Tests
test "verification pool basic" {
const allocator = std.testing.allocator;
var pool = try VerificationPool.init(allocator, .{ .num_workers = 2, .num_piece_buffers = 4 });
defer pool.deinit();
try pool.start();
// Create test data
const test_data = "Hello, World!";
var expected_hash: PieceHash = undefined;
std.crypto.hash.sha2.Sha256.hash(test_data, &expected_hash, .{});
const test_peer_id = [_]u8{0x12} ** 32;
// Queue verification
try pool.queueVerification(
1, // session_id
0, // piece_index
test_data,
expected_hash,
test_peer_id,
);
// Wait for result
var result: ?VerificationResult = null;
var attempts: u32 = 0;
while (result == null and attempts < 100) : (attempts += 1) {
result = pool.getResult();
if (result == null) {
std.Thread.sleep(10 * std.time.ns_per_ms);
}
}
try std.testing.expect(result != null);
try std.testing.expect(result.?.is_valid);
}
test "verification pool invalid hash detection" {
const allocator = std.testing.allocator;
var pool = try VerificationPool.init(allocator, .{ .num_workers = 1, .num_piece_buffers = 4 });
defer pool.deinit();
try pool.start();
// Create test data with wrong hash
const test_data = "Hello, World!";
const wrong_hash: PieceHash = [_]u8{0} ** 32;
const test_peer_id = [_]u8{0x34} ** 32;
// Queue verification
try pool.queueVerification(1, 0, test_data, wrong_hash, test_peer_id);
// Wait for result
var result: ?VerificationResult = null;
var attempts: u32 = 0;
while (result == null and attempts < 100) : (attempts += 1) {
result = pool.getResult();
if (result == null) {
std.Thread.sleep(10 * std.time.ns_per_ms);
}
}
try std.testing.expect(result != null);
try std.testing.expect(!result.?.is_valid);
}