feat: refactor files module: platform abstractions, filesystem error

handling
This commit is contained in:
2026-02-19 11:34:07 -03:00
parent b466979bc7
commit 4c1927588d
16 changed files with 998 additions and 474 deletions

View File

@@ -10,6 +10,7 @@
//! based on success/timeout rates, similar to TCP congestion control. //! based on success/timeout rates, similar to TCP congestion control.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
pub const AdaptiveConcurrencyController = struct { pub const AdaptiveConcurrencyController = struct {
// Configuration (set at init, immutable) // Configuration (set at init, immutable)
@@ -86,7 +87,7 @@ pub const AdaptiveConcurrencyController = struct {
self: *AdaptiveConcurrencyController, self: *AdaptiveConcurrencyController,
current_in_flight: usize, current_in_flight: usize,
) void { ) void {
const now = std.time.nanoTimestamp(); const now = platform_time.nanoTimestamp();
const total = self.cycle_successes + self.cycle_timeouts; const total = self.cycle_successes + self.cycle_timeouts;
if (total > 0) { if (total > 0) {

View File

@@ -4,9 +4,15 @@
//! peer coordination, and download progress tracking. //! peer coordination, and download progress tracking.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const testing = std.testing; const testing = std.testing;
const mem = std.mem; const mem = std.mem;
const atomic = std.atomic;
const fmt = std.fmt; const fmt = std.fmt;
const core = @import("core"); const core = @import("core");
@@ -14,6 +20,7 @@ const Error = core.errors.Error;
const hash = @import("hash.zig"); const hash = @import("hash.zig");
const PieceHash = hash.PieceHash; const PieceHash = hash.PieceHash;
const HashUtils = hash.HashUtils; const HashUtils = hash.HashUtils;
const filesystem = @import("filesystem.zig");
const file = @import("file.zig"); const file = @import("file.zig");
const FileChunker = file.FileChunker; const FileChunker = file.FileChunker;
const FileWriter = file.FileWriter; const FileWriter = file.FileWriter;
@@ -75,7 +82,7 @@ pub const DownloadRequest = struct {
.offset = offset, .offset = offset,
.length = length, .length = length,
.priority = priority, .priority = priority,
.requested_at = std.time.timestamp(), .requested_at = platform_time.timestamp(),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
}; };
} }
@@ -87,7 +94,7 @@ pub const DownloadRequest = struct {
/// Check if request has expired /// Check if request has expired
pub fn isExpired(self: DownloadRequest, timeout_seconds: i64) bool { pub fn isExpired(self: DownloadRequest, timeout_seconds: i64) bool {
return std.time.timestamp() - self.requested_at > timeout_seconds; return platform_time.timestamp() - self.requested_at > timeout_seconds;
} }
}; };
@@ -103,22 +110,22 @@ pub const DownloadRequest = struct {
/// sufficient. If strict transactional semantics are needed, use a mutex. /// sufficient. If strict transactional semantics are needed, use a mutex.
pub const DownloadState = struct { pub const DownloadState = struct {
total_size: u64, total_size: u64,
downloaded_bytes: atomic.Value(u64), downloaded_bytes: AtomicValue(u64),
verified_bytes: atomic.Value(u64), verified_bytes: AtomicValue(u64),
piece_count: u32, piece_count: u32,
completed_pieces: atomic.Value(u32), completed_pieces: AtomicValue(u32),
failed_pieces: atomic.Value(u32), failed_pieces: AtomicValue(u32),
start_time: i64, start_time: i64,
pub fn init(total_size: u64, piece_count: u32) DownloadState { pub fn init(total_size: u64, piece_count: u32) DownloadState {
return DownloadState{ return DownloadState{
.total_size = total_size, .total_size = total_size,
.downloaded_bytes = atomic.Value(u64).init(0), .downloaded_bytes = AtomicValue(u64).init(0),
.verified_bytes = atomic.Value(u64).init(0), .verified_bytes = AtomicValue(u64).init(0),
.piece_count = piece_count, .piece_count = piece_count,
.completed_pieces = atomic.Value(u32).init(0), .completed_pieces = AtomicValue(u32).init(0),
.failed_pieces = atomic.Value(u32).init(0), .failed_pieces = AtomicValue(u32).init(0),
.start_time = std.time.timestamp(), .start_time = platform_time.timestamp(),
}; };
} }
@@ -170,7 +177,7 @@ pub const DownloadState = struct {
/// Get download speed (bytes per second) /// Get download speed (bytes per second)
/// HIGH-4 FIX: Uses acquire ordering to see latest writes. /// HIGH-4 FIX: Uses acquire ordering to see latest writes.
pub fn getDownloadSpeed(self: *DownloadState) f32 { pub fn getDownloadSpeed(self: *DownloadState) f32 {
const elapsed = std.time.timestamp() - self.start_time; const elapsed = platform_time.timestamp() - self.start_time;
if (elapsed <= 0) return 0.0; if (elapsed <= 0) return 0.0;
const downloaded = self.downloaded_bytes.load(.acquire); const downloaded = self.downloaded_bytes.load(.acquire);
@@ -515,11 +522,11 @@ pub const DownloadManager = struct {
file_path: ?[]const u8, file_path: ?[]const u8,
request_timeout: i64, request_timeout: i64,
/// Mutex protecting all hashmaps and lists /// Mutex protecting all hashmaps and lists
manager_mutex: std.Thread.Mutex = .{}, manager_mutex: Mutex = .{},
/// ADAPTIVE: Count of stuck downloads cleaned up since last query /// ADAPTIVE: Count of stuck downloads cleaned up since last query
/// Used by adaptive concurrency controller to detect network issues /// Used by adaptive concurrency controller to detect network issues
stuck_downloads_cleaned: atomic.Value(u32) = atomic.Value(u32).init(0), stuck_downloads_cleaned: AtomicValue(u32) = AtomicValue(u32).init(0),
// PERF: Endgame mode - request remaining pieces from ALL peers // PERF: Endgame mode - request remaining pieces from ALL peers
/// Whether endgame mode is active (last few pieces) /// Whether endgame mode is active (last few pieces)
@@ -542,7 +549,7 @@ pub const DownloadManager = struct {
piece_size: u64, piece_size: u64,
allocator: mem.Allocator, allocator: mem.Allocator,
) Error!DownloadManager { ) Error!DownloadManager {
const seed = std.crypto.random.int(u64); const seed = platform_random.int(u64);
const selector = PieceSelector.init(strategy, seed, allocator); const selector = PieceSelector.init(strategy, seed, allocator);
return DownloadManager{ return DownloadManager{
@@ -819,7 +826,7 @@ pub const DownloadManager = struct {
.offset = 0, .offset = 0,
.length = @intCast(self.piece_size), .length = @intCast(self.piece_size),
.priority = .high, // Boost priority for retried pieces .priority = .high, // Boost priority for retried pieces
.requested_at = std.time.timestamp(), .requested_at = platform_time.timestamp(),
}) catch { }) catch {
std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index}); std.log.warn("CASCADE: Failed to re-queue piece {} after peer disconnect", .{piece_index});
}; };
@@ -1258,7 +1265,7 @@ pub const DownloadManager = struct {
.offset = request.offset, .offset = request.offset,
.length = request.length, .length = request.length,
.downloaded_bytes = 0, .downloaded_bytes = 0,
.started_at = std.time.timestamp(), .started_at = platform_time.timestamp(),
.status = .downloading, .status = .downloading,
}; };
@@ -1564,7 +1571,7 @@ pub const DownloadManager = struct {
/// This function detects and removes such stuck downloads so they can be retried. /// This function detects and removes such stuck downloads so they can be retried.
/// CONCURRENCY FIX: Batch size now matches max_concurrent to handle all stuck downloads in one pass. /// CONCURRENCY FIX: Batch size now matches max_concurrent to handle all stuck downloads in one pass.
fn cleanupStuckActiveDownloadsLocked(self: *DownloadManager, max_concurrent: usize) void { fn cleanupStuckActiveDownloadsLocked(self: *DownloadManager, max_concurrent: usize) void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
// THROUGHPUT FIX: 10 seconds provides a balance between fast retry and avoiding // THROUGHPUT FIX: 10 seconds provides a balance between fast retry and avoiding
// premature retries. 5 seconds was too aggressive and caused excessive retries. // premature retries. 5 seconds was too aggressive and caused excessive retries.
// 15 seconds was too slow for localhost. For WAN, consider 15 seconds. // 15 seconds was too slow for localhost. For WAN, consider 15 seconds.
@@ -1654,7 +1661,7 @@ pub const DownloadManager = struct {
.offset = piece_offset, .offset = piece_offset,
.length = piece_size_u32, .length = piece_size_u32,
.priority = .normal, .priority = .normal,
.requested_at = std.time.timestamp(), .requested_at = platform_time.timestamp(),
// SOCKET FIX: Zero out peer_id so request can be assigned to a different peer. // SOCKET FIX: Zero out peer_id so request can be assigned to a different peer.
// Using the same failed peer_id would cause the retry to fail again. // Using the same failed peer_id would cause the retry to fail again.
// This matches the behavior in cancelActiveDownloadsFromPeerLocked. // This matches the behavior in cancelActiveDownloadsFromPeerLocked.
@@ -1982,7 +1989,7 @@ pub const DownloadManager = struct {
/// PERF: Get info needed for mutex-free pwrite operations /// PERF: Get info needed for mutex-free pwrite operations
/// Returns file handle and calculated absolute offset for direct pwrite /// Returns file handle and calculated absolute offset for direct pwrite
/// Call this while holding mutex, then release mutex and do pwrite directly /// Call this while holding mutex, then release mutex and do pwrite directly
pub fn getWriteInfo(self: *DownloadManager, piece_index: u32, offset: u64) Error!struct { file: std.fs.File, absolute_offset: u64, file_path: []const u8 } { pub fn getWriteInfo(self: *DownloadManager, piece_index: u32, offset: u64) Error!struct { file: filesystem.File, absolute_offset: u64, file_path: []const u8 } {
const writer = self.file_writer orelse return Error.InvalidState; const writer = self.file_writer orelse return Error.InvalidState;
const path = self.file_path orelse return Error.FileError; const path = self.file_path orelse return Error.FileError;
@@ -2004,6 +2011,8 @@ pub const DownloadManager = struct {
/// Verify a piece against expected hash by reading from disk /// Verify a piece against expected hash by reading from disk
pub fn verifyPiece(self: *DownloadManager, piece_index: u32, expected_hash: *const PieceHash) Error!bool { pub fn verifyPiece(self: *DownloadManager, piece_index: u32, expected_hash: *const PieceHash) Error!bool {
if (is_wasm) return Error.OperationNotSupported;
// Get file path // Get file path
const file_path = self.file_path orelse return Error.FileError; const file_path = self.file_path orelse return Error.FileError;
@@ -2018,7 +2027,7 @@ pub const DownloadManager = struct {
const actual_piece_size = @min(self.piece_size, self.total_size - offset); const actual_piece_size = @min(self.piece_size, self.total_size - offset);
// Open file for reading // Open file for reading
var piece_file = std.fs.cwd().openFile(file_path, .{}) catch return Error.FileError; var piece_file = filesystem.FileSystem.openFile(file_path, .{}) catch return Error.FileError;
defer piece_file.close(); defer piece_file.close();
// Seek to piece position // Seek to piece position
@@ -2100,6 +2109,8 @@ pub const DownloadManager = struct {
/// Save current download state to a resume file /// Save current download state to a resume file
/// The resume file stores which pieces are completed, allowing downloads to continue after restart /// The resume file stores which pieces are completed, allowing downloads to continue after restart
pub fn saveResumeState(self: *DownloadManager, resume_path: []const u8) Error!void { pub fn saveResumeState(self: *DownloadManager, resume_path: []const u8) Error!void {
if (is_wasm) return Error.OperationNotSupported;
self.manager_mutex.lock(); self.manager_mutex.lock();
defer self.manager_mutex.unlock(); defer self.manager_mutex.unlock();
@@ -2109,7 +2120,7 @@ pub const DownloadManager = struct {
} }
// Create resume file // Create resume file
var resume_file = std.fs.cwd().createFile(resume_path, .{}) catch return Error.FileError; var resume_file = filesystem.FileSystem.createFile(resume_path, .{}) catch return Error.FileError;
defer resume_file.close(); defer resume_file.close();
// Build header // Build header
@@ -2163,13 +2174,15 @@ pub const DownloadManager = struct {
expected_content_hash: ?[32]u8, expected_content_hash: ?[32]u8,
strategy: SelectionStrategy, strategy: SelectionStrategy,
) Error!?DownloadManager { ) Error!?DownloadManager {
if (is_wasm) return null;
// Validate path // Validate path
if (!path_security.PathValidator.isPathSafe(resume_path)) { if (!path_security.PathValidator.isPathSafe(resume_path)) {
return Error.InvalidData; return Error.InvalidData;
} }
// Open resume file // Open resume file
var resume_file = std.fs.cwd().openFile(resume_path, .{}) catch return null; var resume_file = filesystem.FileSystem.openFile(resume_path, .{}) catch return null;
defer resume_file.close(); defer resume_file.close();
// Read header // Read header
@@ -2278,13 +2291,15 @@ pub const DownloadManager = struct {
self: *DownloadManager, self: *DownloadManager,
piece_hashes: []const PieceHash, piece_hashes: []const PieceHash,
) Error!u32 { ) Error!u32 {
if (is_wasm) return Error.OperationNotSupported;
self.manager_mutex.lock(); self.manager_mutex.lock();
defer self.manager_mutex.unlock(); defer self.manager_mutex.unlock();
const file_path = self.file_path orelse return Error.FileError; const file_path = self.file_path orelse return Error.FileError;
// Open file for reading // Open file for reading
var data_file = std.fs.cwd().openFile(file_path, .{}) catch return Error.FileError; var data_file = filesystem.FileSystem.openFile(file_path, .{}) catch return Error.FileError;
defer data_file.close(); defer data_file.close();
var failed_count: u32 = 0; var failed_count: u32 = 0;
@@ -2369,7 +2384,9 @@ pub const DownloadManager = struct {
/// Delete the resume state file (call after successful download completion) /// Delete the resume state file (call after successful download completion)
pub fn deleteResumeState(resume_path: []const u8) void { pub fn deleteResumeState(resume_path: []const u8) void {
std.fs.cwd().deleteFile(resume_path) catch |err| { if (is_wasm) return;
filesystem.FileSystem.deleteFile(resume_path) catch |err| {
std.log.debug("Failed to delete resume file: {}", .{err}); std.log.debug("Failed to delete resume file: {}", .{err});
}; };
} }
@@ -2425,7 +2442,7 @@ pub const PieceRetryTracker = struct {
/// MEM-2 FIX: Copies peer ID instead of storing reference /// MEM-2 FIX: Copies peer ID instead of storing reference
pub fn recordFailure(self: *PieceRetryTracker, peer: []const u8) void { pub fn recordFailure(self: *PieceRetryTracker, peer: []const u8) void {
self.retry_count += 1; self.retry_count += 1;
self.last_attempt = std.time.milliTimestamp(); self.last_attempt = platform_time.milliTimestamp();
// Copy peer ID to owned array - prevents dangling pointer // Copy peer ID to owned array - prevents dangling pointer
if (peer.len >= 32) { if (peer.len >= 32) {
var peer_copy: [32]u8 = undefined; var peer_copy: [32]u8 = undefined;
@@ -2451,7 +2468,7 @@ pub const PieceRetryTracker = struct {
if (!self.shouldRetry()) return false; if (!self.shouldRetry()) return false;
if (self.retry_count == 0) return true; if (self.retry_count == 0) return true;
const now = std.time.milliTimestamp(); const now = platform_time.milliTimestamp();
const delay = self.getRetryDelay(); const delay = self.getRetryDelay();
return (now - self.last_attempt) >= delay; return (now - self.last_attempt) >= delay;
} }

View File

@@ -9,6 +9,7 @@ const mem = std.mem;
const fs = std.fs; const fs = std.fs;
const fmt = std.fmt; const fmt = std.fmt;
const builtin = @import("builtin"); const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const core = @import("core"); const core = @import("core");
const Error = core.errors.Error; const Error = core.errors.Error;
@@ -185,7 +186,7 @@ pub const FileChunker = struct {
const current_piece_size = @min(self.piece_size, remaining); const current_piece_size = @min(self.piece_size, remaining);
// Read piece data // Read piece data
const piece_data = self.allocator.alloc(u8, current_piece_size) catch return Error.OutOfMemory; const piece_data = self.allocator.alloc(u8, @intCast(current_piece_size)) catch return Error.OutOfMemory;
defer self.allocator.free(piece_data); defer self.allocator.free(piece_data);
const bytes_read = file.read(piece_data) catch return Error.FileError; const bytes_read = file.read(piece_data) catch return Error.FileError;
@@ -227,28 +228,28 @@ pub const FileChunker = struct {
return Error.InvalidData; return Error.InvalidData;
} }
// Open the file // Open the file via FileSystem abstraction
const file = fs.cwd().openFile(file_path, .{}) catch |err| { var file = FileSystem.openFile(file_path, .{}) catch |err| {
std.log.warn("readPiece: openFile failed for '{s}': {}", .{ file_path, err }); std.log.warn("readPiece: openFile failed for '{s}': {}", .{ file_path, err });
return Error.FileError; return Error.FileError;
}; };
defer file.close(); defer file.close();
return self.readPieceInternal(file, piece_index, piece_size); return self.readPieceInternal(&file, piece_index, piece_size);
} }
/// PERF FIX: Public method to read piece from an already-open file handle. /// PERF FIX: Public method to read piece from an already-open file handle.
/// This avoids the overhead of opening/closing the file for every piece. /// This avoids the overhead of opening/closing the file for every piece.
pub fn readPieceFromHandle(self: FileChunker, file: fs.File, piece_index: u32, piece_size: u64) Error![]u8 { pub fn readPieceFromHandle(self: FileChunker, file: *FSFile, piece_index: u32, piece_size: u64) Error![]u8 {
return self.readPieceInternal(file, piece_index, piece_size); return self.readPieceInternal(file, piece_index, piece_size);
} }
fn readPieceInternal(self: FileChunker, file: fs.File, piece_index: u32, piece_size: u64) Error![]u8 { fn readPieceInternal(self: FileChunker, file: *FSFile, piece_index: u32, piece_size: u64) Error![]u8 {
// OVERFLOW FIX: Use checked multiplication to prevent overflow // OVERFLOW FIX: Use checked multiplication to prevent overflow
const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow; const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow;
// THREAD SAFETY FIX: Use preadAll instead of seek+read to allow concurrent reads // THREAD SAFETY FIX: Use preadAll instead of seek+read to allow concurrent reads
// from the same file handle without race conditions on file position. // from the same file handle without race conditions on file position.
const piece_data = self.allocator.alloc(u8, piece_size) catch return Error.OutOfMemory; const piece_data = self.allocator.alloc(u8, @intCast(piece_size)) catch return Error.OutOfMemory;
const bytes_read = file.preadAll(piece_data, offset) catch |err| { const bytes_read = file.preadAll(piece_data, offset) catch |err| {
std.log.warn("readPiece: preadAll failed: {}", .{err}); std.log.warn("readPiece: preadAll failed: {}", .{err});
self.allocator.free(piece_data); self.allocator.free(piece_data);
@@ -274,7 +275,7 @@ pub const FileChunker = struct {
piece_index: u32, piece_index: u32,
piece_data: []const u8, piece_data: []const u8,
) Error!void { ) Error!void {
const file = fs.cwd().openFile(file_path, .{ var file = FileSystem.openFile(file_path, .{
.mode = .write_only, .mode = .write_only,
}) catch return Error.FileError; }) catch return Error.FileError;
defer file.close(); defer file.close();
@@ -776,6 +777,9 @@ pub const FileUtils = struct {
/// Check if sufficient disk space is available /// Check if sufficient disk space is available
pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void { pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void {
// No disk space concept in browser/WASM environment
if (is_wasm) return;
const dir_path = std.fs.path.dirname(path) orelse "."; const dir_path = std.fs.path.dirname(path) orelse ".";
if (builtin.os.tag == .linux or builtin.os.tag == .macos) { if (builtin.os.tag == .linux or builtin.os.tag == .macos) {
@@ -995,7 +999,7 @@ pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void {
pub const FileReader = struct { pub const FileReader = struct {
allocator: mem.Allocator, allocator: mem.Allocator,
file_path: []const u8, file_path: []const u8,
file: fs.File, file: FSFile,
buffer_size: usize, buffer_size: usize,
pub fn init(file_path: []const u8, allocator: mem.Allocator, buffer_size: usize) Error!FileReader { pub fn init(file_path: []const u8, allocator: mem.Allocator, buffer_size: usize) Error!FileReader {
@@ -1004,7 +1008,7 @@ pub const FileReader = struct {
return Error.InvalidData; return Error.InvalidData;
} }
const file = fs.cwd().openFile(file_path, .{}) catch return Error.FileError; const file = FileSystem.openFile(file_path, .{}) catch return Error.FileError;
return FileReader{ return FileReader{
.allocator = allocator, .allocator = allocator,
@@ -1058,7 +1062,7 @@ pub const FileReader = struct {
pub const FileWriter = struct { pub const FileWriter = struct {
allocator: mem.Allocator, allocator: mem.Allocator,
file_path: []const u8, file_path: []const u8,
file: fs.File, file: FSFile,
pub fn init(file_path: []const u8, allocator: mem.Allocator, file_size: ?u64) Error!FileWriter { pub fn init(file_path: []const u8, allocator: mem.Allocator, file_size: ?u64) Error!FileWriter {
return initInternal(file_path, allocator, file_size, true); return initInternal(file_path, allocator, file_size, true);
@@ -1090,14 +1094,14 @@ pub const FileWriter = struct {
} }
// DISK VERIFY FIX: Open with read=true to allow pread for disk verification // DISK VERIFY FIX: Open with read=true to allow pread for disk verification
const file = fs.cwd().createFile(file_path, .{ var file = FileSystem.createFile(file_path, .{
.truncate = truncate, .truncate = truncate,
.read = true, .read = true,
}) catch return Error.FileError; }) catch return Error.FileError;
// PERF: Pre-allocate file if size is known (reduces fragmentation, faster writes) // PERF: Pre-allocate file if size is known (reduces fragmentation, faster writes)
if (file_size) |size| { if (file_size) |size| {
preallocateFile(file, size); preallocateFile(&file, size);
} }
return FileWriter{ return FileWriter{
@@ -1108,12 +1112,17 @@ pub const FileWriter = struct {
} }
/// PERF: Pre-allocate file space to avoid fragmentation and allocation during writes /// PERF: Pre-allocate file space to avoid fragmentation and allocation during writes
fn preallocateFile(file: fs.File, size: u64) void { fn preallocateFile(file: *FSFile, size: u64) void {
// No pre-allocation on WASM
if (is_wasm) return;
// Try fallocate first (Linux) - actually allocates blocks // Try fallocate first (Linux) - actually allocates blocks
if (builtin.os.tag == .linux) { if (builtin.os.tag == .linux) {
if (!is_wasm) {
// FALLOC_FL_KEEP_SIZE = 0x01 - allocate without changing file size // FALLOC_FL_KEEP_SIZE = 0x01 - allocate without changing file size
const FALLOC_FL_KEEP_SIZE = 0x01; const FALLOC_FL_KEEP_SIZE = 0x01;
const fd = file.handle; const real_file = file.impl.real;
const fd = real_file.handle;
const result = std.os.linux.syscall4(.fallocate, const result = std.os.linux.syscall4(.fallocate,
@as(usize, @intCast(fd)), @as(usize, @intCast(fd)),
@as(usize, FALLOC_FL_KEEP_SIZE), @as(usize, FALLOC_FL_KEEP_SIZE),
@@ -1124,6 +1133,7 @@ pub const FileWriter = struct {
std.log.debug("PERF: Pre-allocated {} MB with fallocate", .{size / (1024 * 1024)}); std.log.debug("PERF: Pre-allocated {} MB with fallocate", .{size / (1024 * 1024)});
return; return;
} }
}
// fallocate failed, fall through to ftruncate // fallocate failed, fall through to ftruncate
} }
@@ -1174,7 +1184,9 @@ pub const FileWriter = struct {
} }
/// Get the underlying file handle for direct pwrite operations outside mutex /// Get the underlying file handle for direct pwrite operations outside mutex
pub fn getFileHandle(self: *const FileWriter) std.fs.File { /// Returns a copy of the FSFile — safe because pwriteAll/sync use the fd/file_id,
/// not the position field.
pub fn getFileHandle(self: *const FileWriter) FSFile {
return self.file; return self.file;
} }
@@ -1186,8 +1198,9 @@ pub const FileWriter = struct {
// On macOS, fsync only syncs to the drive's buffer, not the physical disk. // On macOS, fsync only syncs to the drive's buffer, not the physical disk.
// F_FULLFSYNC forces the drive to flush its internal cache to the platters. // F_FULLFSYNC forces the drive to flush its internal cache to the platters.
if (builtin.os.tag == .macos) { if (!is_wasm and builtin.os.tag == .macos) {
const handle = self.file.handle; const real_file = self.file.impl.real;
const handle = real_file.handle;
const F_FULLFSYNC = 51; // From <fcntl.h> const F_FULLFSYNC = 51; // From <fcntl.h>
_ = std.c.fcntl(handle, F_FULLFSYNC, @as(c_int, 0)); _ = std.c.fcntl(handle, F_FULLFSYNC, @as(c_int, 0));
// Ignore error - not all drives support F_FULLFSYNC // Ignore error - not all drives support F_FULLFSYNC
@@ -1237,11 +1250,11 @@ pub const MMAP_MAX_SIZE: u64 = 2 * 1024 * 1024 * 1024;
/// ``` /// ```
pub const MappedFile = struct { pub const MappedFile = struct {
/// Pointer to mapped memory region /// Pointer to mapped memory region
data: []align(std.heap.page_size_min) u8, data: if (is_wasm) []u8 else []align(std.heap.page_size_min) u8,
/// Original file size /// Original file size
file_size: u64, file_size: u64,
/// File handle (kept open while mapped) /// File handle (kept open while mapped) — void on WASM (mmap not supported)
file: fs.File, file: if (is_wasm) void else fs.File,
/// Initialize memory-mapped file for reading /// Initialize memory-mapped file for reading
/// Returns error if file is too small for mmap benefit or too large /// Returns error if file is too small for mmap benefit or too large
@@ -1251,6 +1264,8 @@ pub const MappedFile = struct {
/// Initialize with custom size limits /// Initialize with custom size limits
pub fn initWithLimits(file_path: []const u8, min_size: u64, max_size: u64) Error!MappedFile { pub fn initWithLimits(file_path: []const u8, min_size: u64, max_size: u64) Error!MappedFile {
if (is_wasm) return Error.OperationNotSupported;
// Validate path // Validate path
if (!PathValidator.isPathSafe(file_path)) { if (!PathValidator.isPathSafe(file_path)) {
return Error.InvalidData; return Error.InvalidData;
@@ -1289,7 +1304,9 @@ pub const MappedFile = struct {
} }
/// Initialize from an already-open file handle /// Initialize from an already-open file handle
pub fn initFromHandle(file: fs.File, file_size: u64) Error!MappedFile { pub fn initFromHandle(file: if (is_wasm) void else fs.File, file_size: u64) Error!MappedFile {
if (is_wasm) return Error.OperationNotSupported;
if (file_size < MMAP_MIN_SIZE) { if (file_size < MMAP_MIN_SIZE) {
return Error.InvalidData; return Error.InvalidData;
} }
@@ -1347,27 +1364,28 @@ pub const MappedFile = struct {
/// Advise the kernel about access patterns (optimization hint) /// Advise the kernel about access patterns (optimization hint)
pub fn adviseSequential(self: *MappedFile) void { pub fn adviseSequential(self: *MappedFile) void {
if (builtin.os.tag == .linux) { if (!is_wasm and builtin.os.tag == .linux) {
_ = std.posix.madvise(self.data, std.posix.MADV.SEQUENTIAL); _ = std.posix.madvise(self.data, std.posix.MADV.SEQUENTIAL);
} }
} }
/// Advise random access pattern /// Advise random access pattern
pub fn adviseRandom(self: *MappedFile) void { pub fn adviseRandom(self: *MappedFile) void {
if (builtin.os.tag == .linux) { if (!is_wasm and builtin.os.tag == .linux) {
_ = std.posix.madvise(self.data, std.posix.MADV.RANDOM); _ = std.posix.madvise(self.data, std.posix.MADV.RANDOM);
} }
} }
/// Pre-fault pages into memory (reduce page faults during reads) /// Pre-fault pages into memory (reduce page faults during reads)
pub fn prefault(self: *MappedFile) void { pub fn prefault(self: *MappedFile) void {
if (builtin.os.tag == .linux) { if (!is_wasm and builtin.os.tag == .linux) {
_ = std.posix.madvise(self.data, std.posix.MADV.WILLNEED); _ = std.posix.madvise(self.data, std.posix.MADV.WILLNEED);
} }
} }
/// Release resources /// Release resources
pub fn deinit(self: *MappedFile) void { pub fn deinit(self: *MappedFile) void {
if (is_wasm) return;
// Unmap memory // Unmap memory
std.posix.munmap(self.data); std.posix.munmap(self.data);
// Close file // Close file
@@ -1375,7 +1393,9 @@ pub const MappedFile = struct {
} }
/// Platform-specific mmap implementation /// Platform-specific mmap implementation
fn mapFile(file: fs.File, size: u64) ![]align(std.heap.page_size_min) u8 { fn mapFile(file: if (is_wasm) void else fs.File, size: u64) !if (is_wasm) []u8 else []align(std.heap.page_size_min) u8 {
if (is_wasm) return error.OperationNotSupported;
const len: usize = @intCast(size); const len: usize = @intCast(size);
// Use mmap on POSIX systems // Use mmap on POSIX systems

View File

@@ -1,13 +1,14 @@
//! Filesystem Abstraction Layer //! Filesystem Abstraction Layer
//! //!
//! Provides a unified interface for filesystem operations that can be backed by //! 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. //! either the real filesystem (std.fs), an in-memory mock filesystem for testing,
//! or a WASM/JS-backed filesystem for browser environments.
//! //!
//! Usage: //! Usage:
//! ```zig //! ```zig
//! const FS = @import("filesystem.zig").FileSystem; //! const FS = @import("filesystem.zig").FileSystem;
//! //!
//! // Opens file using current backend (real or mock) //! // Opens file using current backend (real, mock, or wasm)
//! var file = try FS.openFile("/path/to/file", .{}); //! var file = try FS.openFile("/path/to/file", .{});
//! defer file.close(); //! defer file.close();
//! //!
@@ -18,10 +19,13 @@
//! To use MockFS in tests, set `use_mock_fs = true` before importing. //! To use MockFS in tests, set `use_mock_fs = true` before importing.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const builtin = @import("builtin"); const builtin = @import("builtin");
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
const mock_fs = @import("mock_fs.zig"); const mock_fs = @import("mock_fs.zig");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
/// Compile-time flag to enable mock filesystem /// Compile-time flag to enable mock filesystem
/// Set this in test files before importing filesystem.zig /// Set this in test files before importing filesystem.zig
pub var use_mock_fs: bool = false; pub var use_mock_fs: bool = false;
@@ -30,22 +34,57 @@ pub var use_mock_fs: bool = false;
/// Must be initialized before use when use_mock_fs is true /// Must be initialized before use when use_mock_fs is true
pub var mock_instance: ?*mock_fs.MockFS = null; pub var mock_instance: ?*mock_fs.MockFS = null;
// ============================================================================
// WASM extern "env" file functions (only compiled for WASM targets)
// These are implemented by the JS host (browser/host/file-host.js)
// ============================================================================
const wasm_externs = if (is_wasm) struct {
extern "env" fn js_file_open(path_ptr: [*]const u8, path_len: u32, read_only: u32) i32;
extern "env" fn js_file_create(path_ptr: [*]const u8, path_len: u32) i32;
extern "env" fn js_file_read(file_id: u32, buf_ptr: [*]u8, buf_len: u32, offset: u64) i32;
extern "env" fn js_file_write(file_id: u32, data_ptr: [*]const u8, data_len: u32, offset: u64) i32;
extern "env" fn js_file_get_size(file_id: u32) i64;
extern "env" fn js_file_close(file_id: u32) void;
extern "env" fn js_file_exists(path_ptr: [*]const u8, path_len: u32) u32;
extern "env" fn js_file_delete(path_ptr: [*]const u8, path_len: u32) u32;
extern "env" fn js_file_rename(old_ptr: [*]const u8, old_len: u32, new_ptr: [*]const u8, new_len: u32) u32;
extern "env" fn js_file_mkdir(path_ptr: [*]const u8, path_len: u32) u32;
} else struct {};
/// File kind (matches std.fs.File.Kind subset)
pub const FileKind = enum {
file,
directory,
unknown,
};
/// File statistics /// File statistics
pub const Stat = struct { pub const Stat = struct {
size: u64, size: u64,
ctime: i128, ctime: i128,
mtime: i128, mtime: i128,
atime: i128, atime: i128,
kind: FileKind = .file,
}; };
/// Abstract file handle that wraps either std.fs.File or MockFileHandle /// WASM file state — JS-managed handle ID with position tracking
pub const WasmFileState = struct {
file_id: u32,
position: u64,
read_only: bool,
};
/// Abstract file handle that wraps std.fs.File, MockFileHandle, or WasmFileState
pub const File = struct { pub const File = struct {
impl: FileImpl, impl: FileImpl,
const FileImpl = union(enum) { /// On WASM: mock + wasm variants only (no real filesystem).
real: std.fs.File, /// On native: real + mock variants only (no wasm extern calls).
mock: MockFileState, const FileImpl = if (is_wasm)
}; union(enum) { mock: MockFileState, wasm: WasmFileState }
else
union(enum) { real: std.fs.File, mock: MockFileState };
const MockFileState = struct { const MockFileState = struct {
fs: *mock_fs.MockFS, fs: *mock_fs.MockFS,
@@ -54,126 +93,56 @@ pub const File = struct {
read_only: bool, read_only: bool,
}; };
/// Read data from file at current position // ---- Mock helpers (shared by both WASM and native) ----
pub fn read(self: *File, buffer: []u8) !usize {
switch (self.impl) { fn mockRead(state: *MockFileState, buffer: []u8) !usize {
.real => |f| return f.read(buffer),
.mock => |*state| {
const file = state.fs.files.get(state.path) orelse return error.FileNotFound; const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
const content = file.data; const content = file.data;
if (state.position >= content.len) return 0;
if (state.position >= content.len) {
return 0; // EOF
}
const available = content.len - @as(usize, @intCast(state.position)); const available = content.len - @as(usize, @intCast(state.position));
const to_read = @min(buffer.len, available); const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[@intCast(state.position)..][0..to_read]); @memcpy(buffer[0..to_read], content[@intCast(state.position)..][0..to_read]);
state.position += to_read; state.position += to_read;
return to_read; return to_read;
},
}
} }
/// Read data from file at specific offset (pread) fn mockPreadAll(state: MockFileState, buffer: []u8, offset: u64) !usize {
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 file = state.fs.files.get(state.path) orelse return error.FileNotFound;
const content = file.data; const content = file.data;
const off: usize = @intCast(@min(offset, content.len)); const off: usize = @intCast(@min(offset, content.len));
if (off >= content.len) { if (off >= content.len) return 0;
return 0;
}
const available = content.len - off; const available = content.len - off;
const to_read = @min(buffer.len, available); const to_read = @min(buffer.len, available);
@memcpy(buffer[0..to_read], content[off..][0..to_read]); @memcpy(buffer[0..to_read], content[off..][0..to_read]);
return to_read; return to_read;
},
}
} }
/// Write data to file at current position fn mockWrite(state: *MockFileState, data: []const u8) !usize {
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; if (state.read_only) return error.AccessDenied;
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound; const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
// Extend file if necessary
const end_pos = state.position + data.len; const end_pos = state.position + data.len;
if (end_pos > file.data.len) { if (end_pos > file.data.len) {
file.resize(end_pos) catch return error.OutOfMemory; file.resize(@intCast(end_pos)) catch return error.OutOfMemory;
} }
// Copy data
const pos: usize = @intCast(state.position); const pos: usize = @intCast(state.position);
@memcpy(file.data[pos..][0..data.len], data); @memcpy(file.data[pos..][0..data.len], data);
state.position += data.len; state.position += data.len;
file.modified_at = std.time.timestamp(); file.modified_at = platform_time.timestamp();
return data.len; return data.len;
},
}
} }
/// Write data at specific offset (pwrite) fn mockPwriteAll(state: MockFileState, data: []const u8, offset: u64) !void {
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; if (state.read_only) return error.AccessDenied;
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound; const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
const off: usize = @intCast(offset); const off: usize = @intCast(offset);
// Extend file if necessary
if (off + data.len > file.data.len) { if (off + data.len > file.data.len) {
file.resize(off + data.len) catch return error.OutOfMemory; file.resize(off + data.len) catch return error.OutOfMemory;
} }
// Copy data
@memcpy(file.data[off..][0..data.len], data); @memcpy(file.data[off..][0..data.len], data);
file.modified_at = std.time.timestamp(); file.modified_at = platform_time.timestamp();
},
}
} }
/// Seek to position fn mockStat(state: MockFileState) !Stat {
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; const file = state.fs.files.get(state.path) orelse return error.FileNotFound;
return Stat{ return Stat{
.size = file.data.len, .size = file.data.len,
@@ -181,23 +150,222 @@ pub const File = struct {
.mtime = file.modified_at, .mtime = file.modified_at,
.atime = file.modified_at, .atime = file.modified_at,
}; };
}
fn mockSetEndPos(state: MockFileState, pos: u64) !void {
const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound;
file.resize(pos) catch return error.OutOfMemory;
}
// ---- Public API ----
/// Read data from file at current position
pub fn read(self: *File, buffer: []u8) !usize {
if (is_wasm) {
return switch (self.impl) {
.mock => |*state| mockRead(state, buffer),
.wasm => |*state| {
const n = wasm_externs.js_file_read(state.file_id, buffer.ptr, @intCast(buffer.len), state.position);
if (n < 0) return error.InputOutput;
const bytes: usize = @intCast(n);
state.position += bytes;
return bytes;
}, },
};
} else {
return switch (self.impl) {
.real => |f| f.read(buffer),
.mock => |*state| mockRead(state, buffer),
};
} }
} }
/// Sync file to disk (no-op for mock) /// Read exactly buffer.len bytes (or until EOF)
pub fn readAll(self: *File, buffer: []u8) !usize {
var total: usize = 0;
while (total < buffer.len) {
const n = try self.read(buffer[total..]);
if (n == 0) break;
total += n;
}
return total;
}
/// Read data from file at specific offset (pread)
pub fn preadAll(self: *File, buffer: []u8, offset: u64) !usize {
if (is_wasm) {
return switch (self.impl) {
.mock => |state| mockPreadAll(state, buffer, offset),
.wasm => |state| {
const n = wasm_externs.js_file_read(state.file_id, buffer.ptr, @intCast(buffer.len), offset);
if (n < 0) return error.InputOutput;
return @intCast(n);
},
};
} else {
return switch (self.impl) {
.real => |f| f.preadAll(buffer, offset),
.mock => |state| mockPreadAll(state, buffer, offset),
};
}
}
/// Write data to file at current position
pub fn write(self: *File, data: []const u8) !usize {
if (is_wasm) {
return switch (self.impl) {
.mock => |*state| mockWrite(state, data),
.wasm => |*state| {
if (state.read_only) return error.AccessDenied;
const n = wasm_externs.js_file_write(state.file_id, data.ptr, @intCast(data.len), state.position);
if (n < 0) return error.InputOutput;
const bytes: usize = @intCast(n);
state.position += bytes;
return bytes;
},
};
} else {
return switch (self.impl) {
.real => |f| f.write(data),
.mock => |*state| mockWrite(state, data),
};
}
}
/// Write all data to file at current position
pub fn writeAll(self: *File, data: []const u8) !void {
var written: usize = 0;
while (written < data.len) {
const n = try self.write(data[written..]);
if (n == 0) return error.InputOutput;
written += n;
}
}
/// Write data at specific offset (pwrite)
pub fn pwriteAll(self: *File, data: []const u8, offset: u64) !void {
if (is_wasm) {
return switch (self.impl) {
.mock => |state| mockPwriteAll(state, data, offset),
.wasm => |state| {
if (state.read_only) return error.AccessDenied;
const n = wasm_externs.js_file_write(state.file_id, data.ptr, @intCast(data.len), offset);
if (n < 0) return error.InputOutput;
},
};
} else {
return switch (self.impl) {
.real => |f| try f.pwriteAll(data, offset),
.mock => |state| mockPwriteAll(state, data, offset),
};
}
}
/// Seek to position
pub fn seekTo(self: *File, position: u64) !void {
if (is_wasm) {
switch (self.impl) {
.mock => |*state| state.position = position,
.wasm => |*state| state.position = position,
}
} else {
switch (self.impl) {
.real => |f| try f.seekTo(position),
.mock => |*state| state.position = position,
}
}
}
/// Get current position
pub fn getPos(self: *File) !u64 {
if (is_wasm) {
return switch (self.impl) {
.mock => |state| state.position,
.wasm => |state| state.position,
};
} else {
return switch (self.impl) {
.real => |f| f.getPos(),
.mock => |state| state.position,
};
}
}
/// Get file end position (size)
pub fn getEndPos(self: *File) !u64 {
const s = try self.stat();
return s.size;
}
/// Set file end position (truncate/extend)
pub fn setEndPos(self: *File, pos: u64) !void {
if (is_wasm) {
switch (self.impl) {
.mock => |state| try mockSetEndPos(state, pos),
.wasm => {}, // No-op — JS manages sizing automatically
}
} else {
switch (self.impl) {
.real => |f| try f.setEndPos(pos),
.mock => |state| try mockSetEndPos(state, pos),
}
}
}
/// Get file statistics
pub fn stat(self: *File) !Stat {
if (is_wasm) {
return switch (self.impl) {
.mock => |state| mockStat(state),
.wasm => |state| {
const size = wasm_externs.js_file_get_size(state.file_id);
if (size < 0) return error.InputOutput;
const now = platform_time.timestamp();
return Stat{ .size = @intCast(size), .ctime = now, .mtime = now, .atime = now };
},
};
} else {
return switch (self.impl) {
.real => |f| {
const s = try f.stat();
const kind: FileKind = switch (s.kind) {
.directory => .directory,
.file => .file,
else => .unknown,
};
return Stat{ .size = s.size, .ctime = s.ctime, .mtime = s.mtime, .atime = s.atime, .kind = kind };
},
.mock => |state| mockStat(state),
};
}
}
/// Sync file to disk (no-op for mock and wasm)
pub fn sync(self: *File) !void { pub fn sync(self: *File) !void {
if (is_wasm) {
switch (self.impl) {
.mock, .wasm => {},
}
} else {
switch (self.impl) { switch (self.impl) {
.real => |f| try f.sync(), .real => |f| try f.sync(),
.mock => {}, .mock => {},
} }
} }
}
/// Close file handle /// Close file handle
pub fn close(self: *File) void { pub fn close(self: *File) void {
if (is_wasm) {
switch (self.impl) {
.mock => {},
.wasm => |state| wasm_externs.js_file_close(state.file_id),
}
} else {
switch (self.impl) { switch (self.impl) {
.real => |f| f.close(), .real => |f| f.close(),
.mock => {}, // MockFS doesn't track open handles .mock => {},
}
} }
} }
}; };
@@ -206,6 +374,26 @@ pub const File = struct {
pub const FileSystem = struct { pub const FileSystem = struct {
/// Open an existing file /// Open an existing file
pub fn openFile(path: []const u8, flags: std.fs.File.OpenFlags) !File { pub fn openFile(path: []const u8, flags: std.fs.File.OpenFlags) !File {
if (is_wasm) {
if (mock_instance) |mfs| {
if (!mfs.fileExists(path)) return error.FileNotFound;
return File{ .impl = .{ .mock = .{
.fs = mfs,
.path = path,
.position = 0,
.read_only = flags.mode == .read_only,
} } };
}
const read_only: u32 = if (flags.mode == .read_only) 1 else 0;
const fid = wasm_externs.js_file_open(path.ptr, @intCast(path.len), read_only);
if (fid < 0) return error.FileNotFound;
return File{ .impl = .{ .wasm = .{
.file_id = @intCast(fid),
.position = 0,
.read_only = read_only == 1,
} } };
}
if (mock_instance) |mfs| { if (mock_instance) |mfs| {
// Check if file exists in mock // Check if file exists in mock
if (!mfs.fileExists(path)) { if (!mfs.fileExists(path)) {
@@ -230,6 +418,28 @@ pub const FileSystem = struct {
/// Create a new file or truncate existing /// Create a new file or truncate existing
pub fn createFile(path: []const u8, flags: std.fs.File.CreateFlags) !File { pub fn createFile(path: []const u8, flags: std.fs.File.CreateFlags) !File {
if (is_wasm) {
if (mock_instance) |mfs| {
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,
} } };
}
const fid = wasm_externs.js_file_create(path.ptr, @intCast(path.len));
if (fid < 0) return error.AccessDenied;
return File{ .impl = .{ .wasm = .{
.file_id = @intCast(fid),
.position = 0,
.read_only = false,
} } };
}
if (mock_instance) |mfs| { if (mock_instance) |mfs| {
// Create file in mock (or truncate if exists) // Create file in mock (or truncate if exists)
mfs.writeFile(path, "") catch |err| switch (err) { mfs.writeFile(path, "") catch |err| switch (err) {
@@ -255,6 +465,11 @@ pub const FileSystem = struct {
/// Check if file exists /// Check if file exists
pub fn fileExists(path: []const u8) bool { pub fn fileExists(path: []const u8) bool {
if (is_wasm) {
if (mock_instance) |mfs| return mfs.fileExists(path);
return wasm_externs.js_file_exists(path.ptr, @intCast(path.len)) != 0;
}
if (mock_instance) |mfs| { if (mock_instance) |mfs| {
return mfs.fileExists(path); return mfs.fileExists(path);
} else { } else {
@@ -265,6 +480,20 @@ pub const FileSystem = struct {
/// Delete a file /// Delete a file
pub fn deleteFile(path: []const u8) !void { pub fn deleteFile(path: []const u8) !void {
if (is_wasm) {
if (mock_instance) |mfs| {
mfs.deleteFile(path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound,
else => return error.AccessDenied,
};
return;
}
if (wasm_externs.js_file_delete(path.ptr, @intCast(path.len)) == 0) {
return error.FileNotFound;
}
return;
}
if (mock_instance) |mfs| { if (mock_instance) |mfs| {
mfs.deleteFile(path) catch |err| switch (err) { mfs.deleteFile(path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound, error.FileNotFound => return error.FileNotFound,
@@ -277,6 +506,20 @@ pub const FileSystem = struct {
/// Create directory (and parents) /// Create directory (and parents)
pub fn makePath(path: []const u8) !void { pub fn makePath(path: []const u8) !void {
if (is_wasm) {
if (mock_instance) |mfs| {
mfs.makeDir(path) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return error.AccessDenied,
};
return;
}
if (wasm_externs.js_file_mkdir(path.ptr, @intCast(path.len)) == 0) {
return error.AccessDenied;
}
return;
}
if (mock_instance) |mfs| { if (mock_instance) |mfs| {
mfs.makeDir(path) catch |err| switch (err) { mfs.makeDir(path) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory, error.OutOfMemory => return error.OutOfMemory,
@@ -289,6 +532,21 @@ pub const FileSystem = struct {
/// Rename/move a file /// Rename/move a file
pub fn rename(old_path: []const u8, new_path: []const u8) !void { pub fn rename(old_path: []const u8, new_path: []const u8) !void {
if (is_wasm) {
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,
};
return;
}
if (wasm_externs.js_file_rename(old_path.ptr, @intCast(old_path.len), new_path.ptr, @intCast(new_path.len)) == 0) {
return error.FileNotFound;
}
return;
}
if (mock_instance) |mfs| { if (mock_instance) |mfs| {
mfs.rename(old_path, new_path) catch |err| switch (err) { mfs.rename(old_path, new_path) catch |err| switch (err) {
error.FileNotFound => return error.FileNotFound, error.FileNotFound => return error.FileNotFound,
@@ -299,6 +557,39 @@ pub const FileSystem = struct {
try std.fs.cwd().rename(old_path, new_path); try std.fs.cwd().rename(old_path, new_path);
} }
} }
/// Check if path is a directory (for manager.zig's resolveOutputPath)
pub fn statFile(path: []const u8) !Stat {
if (is_wasm) {
// On WASM, open the file to get its size (no directory concept)
var f = openFile(path, .{}) catch return error.FileNotFound;
defer f.close();
return f.stat();
}
if (mock_instance) |mfs| {
if (mfs.dirExists(path)) {
return Stat{ .size = 0, .ctime = 0, .mtime = 0, .atime = 0, .kind = .directory };
}
var f = try openFile(path, .{});
defer f.close();
return f.stat();
}
const s = try std.fs.cwd().statFile(path);
const kind: FileKind = switch (s.kind) {
.directory => .directory,
.file => .file,
else => .unknown,
};
return Stat{
.size = s.size,
.ctime = s.ctime,
.mtime = s.mtime,
.atime = s.atime,
.kind = kind,
};
}
}; };
// ============================================================================ // ============================================================================
@@ -434,3 +725,48 @@ test "FileSystem: mock delete and rename" {
try FileSystem.deleteFile("/new.txt"); try FileSystem.deleteFile("/new.txt");
try std.testing.expect(!FileSystem.fileExists("/new.txt")); try std.testing.expect(!FileSystem.fileExists("/new.txt"));
} }
test "FileSystem: mock readAll and writeAll" {
const allocator = std.testing.allocator;
var mfs = mock_fs.MockFS.init(allocator);
defer mfs.deinit();
mock_instance = &mfs;
defer {
mock_instance = null;
}
var file = try FileSystem.createFile("/rw.txt", .{});
try file.writeAll("Hello, readAll!");
file.close();
var file2 = try FileSystem.openFile("/rw.txt", .{});
defer file2.close();
var buf: [100]u8 = undefined;
const n = try file2.readAll(&buf);
try std.testing.expectEqualStrings("Hello, readAll!", buf[0..n]);
}
test "FileSystem: mock getEndPos and setEndPos" {
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("/size.txt", "12345");
var file = try FileSystem.openFile("/size.txt", .{ .mode = .read_write });
defer file.close();
const end = try file.getEndPos();
try std.testing.expectEqual(@as(u64, 5), end);
try file.setEndPos(10);
const end2 = try file.getEndPos();
try std.testing.expectEqual(@as(u64, 10), end2);
}

View File

@@ -7,6 +7,7 @@
//! acceleration (SHA-NI on x86_64, SHA2 extensions on ARM64) when available. //! acceleration (SHA-NI on x86_64, SHA2 extensions on ARM64) when available.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const testing = std.testing; const testing = std.testing;
const crypto = std.crypto; const crypto = std.crypto;
const mem = std.mem; const mem = std.mem;
@@ -157,8 +158,8 @@ pub const FileMetadata = struct {
.size = size, .size = size,
.piece_count = @as(u32, @intCast(piece_hashes.len)), .piece_count = @as(u32, @intCast(piece_hashes.len)),
.piece_hashes = piece_hashes, .piece_hashes = piece_hashes,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.modified_at = std.time.timestamp(), .modified_at = platform_time.timestamp(),
}; };
} }
@@ -274,7 +275,7 @@ pub const HashPool = struct {
) Error!VerificationBatch { ) Error!VerificationBatch {
var results: std.ArrayList(VerificationResult) = .{}; var results: std.ArrayList(VerificationResult) = .{};
errdefer results.deinit(self.allocator); errdefer results.deinit(self.allocator);
const start_time = std.time.milliTimestamp(); const start_time = platform_time.milliTimestamp();
var valid_count: u32 = 0; var valid_count: u32 = 0;
for (piece_datas, 0..) |piece_data, i| { for (piece_datas, 0..) |piece_data, i| {
@@ -298,7 +299,7 @@ pub const HashPool = struct {
} }
} }
const end_time = std.time.milliTimestamp(); const end_time = platform_time.milliTimestamp();
const verification_time = @as(u64, @intCast(end_time - start_time)); const verification_time = @as(u64, @intCast(end_time - start_time));
return VerificationBatch{ return VerificationBatch{

View File

@@ -18,11 +18,16 @@
//! IMPORTANT: Never acquire lower-level locks (0-4) while holding Level 5 locks. //! IMPORTANT: Never acquire lower-level locks (0-4) while holding Level 5 locks.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const builtin = @import("builtin"); const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const testing = std.testing; const testing = std.testing;
const mem = std.mem; const mem = std.mem;
const fmt = std.fmt; const fmt = std.fmt;
const atomic = std.atomic;
const core = @import("core"); const core = @import("core");
const Error = core.errors.Error; const Error = core.errors.Error;
@@ -31,6 +36,7 @@ const HashUtils = hash_mod.HashUtils;
const FileMetadata = hash_mod.FileMetadata; const FileMetadata = hash_mod.FileMetadata;
const PieceHash = hash_mod.PieceHash; const PieceHash = hash_mod.PieceHash;
const ContentHash = hash_mod.ContentHash; const ContentHash = hash_mod.ContentHash;
const filesystem = @import("filesystem.zig");
const file_mod = @import("file.zig"); const file_mod = @import("file.zig");
const FileChunker = file_mod.FileChunker; const FileChunker = file_mod.FileChunker;
const FileWriter = file_mod.FileWriter; const FileWriter = file_mod.FileWriter;
@@ -161,7 +167,7 @@ pub const PeerReputation = struct {
} }
// MED-4 FIX: Global configurable blacklist duration (thread-safe) // MED-4 FIX: Global configurable blacklist duration (thread-safe)
var configured_base_duration: std.atomic.Value(i64) = std.atomic.Value(i64).init(DEFAULT_BLACKLIST_DURATION_SECONDS); var configured_base_duration: AtomicValue(i64) = AtomicValue(i64).init(DEFAULT_BLACKLIST_DURATION_SECONDS);
/// MED-4 FIX: Configure the base blacklist duration /// MED-4 FIX: Configure the base blacklist duration
/// MED-6 FIX: Uses .release ordering for security config to ensure visibility /// MED-6 FIX: Uses .release ordering for security config to ensure visibility
@@ -224,7 +230,7 @@ pub const PeerReputation = struct {
/// MED-4 FIX: Uses exponential backoff for repeat offenders /// MED-4 FIX: Uses exponential backoff for repeat offenders
pub fn recordBadPiece(self: *PeerReputation) void { pub fn recordBadPiece(self: *PeerReputation) void {
self.bad_pieces += 1; self.bad_pieces += 1;
self.last_bad_piece_time = std.time.timestamp(); self.last_bad_piece_time = platform_time.timestamp();
// Blacklist peer if they've sent too many bad pieces // Blacklist peer if they've sent too many bad pieces
if (self.bad_pieces >= MAX_BAD_PIECES) { if (self.bad_pieces >= MAX_BAD_PIECES) {
@@ -234,7 +240,7 @@ pub const PeerReputation = struct {
const base = getBaseBlacklistDuration(); const base = getBaseBlacklistDuration();
const multiplier: i64 = @as(i64, 1) << @min(self.blacklist_count - 1, 10); // Cap at 2^10 = 1024x const multiplier: i64 = @as(i64, 1) << @min(self.blacklist_count - 1, 10); // Cap at 2^10 = 1024x
const duration = @min(base * multiplier, MAX_BLACKLIST_DURATION_SECONDS); const duration = @min(base * multiplier, MAX_BLACKLIST_DURATION_SECONDS);
self.blacklisted_until = std.time.timestamp() + duration; self.blacklisted_until = platform_time.timestamp() + duration;
std.log.info("MED-4: Peer blacklisted for {}s (offense #{}, base={}s)", .{ std.log.info("MED-4: Peer blacklisted for {}s (offense #{}, base={}s)", .{
duration, duration,
self.blacklist_count, self.blacklist_count,
@@ -250,7 +256,7 @@ pub const PeerReputation = struct {
/// Check if peer is currently blacklisted /// Check if peer is currently blacklisted
pub fn isBlacklisted(self: *const PeerReputation) bool { pub fn isBlacklisted(self: *const PeerReputation) bool {
return std.time.timestamp() < self.blacklisted_until; return platform_time.timestamp() < self.blacklisted_until;
} }
/// Get reputation score (0.0 to 1.0, higher is better) /// Get reputation score (0.0 to 1.0, higher is better)
@@ -304,7 +310,7 @@ pub const PeerResponseTracker = struct {
pub fn init() PeerSlotInfo { pub fn init() PeerSlotInfo {
return .{ return .{
.queued_count = 0, .queued_count = 0,
.last_activity = std.time.timestamp(), .last_activity = platform_time.timestamp(),
.queued_bytes = 0, .queued_bytes = 0,
}; };
} }
@@ -417,7 +423,7 @@ pub const PeerResponseTracker = struct {
} }
gop.value_ptr.queued_count += 1; gop.value_ptr.queued_count += 1;
gop.value_ptr.queued_bytes += piece_size; gop.value_ptr.queued_bytes += piece_size;
gop.value_ptr.last_activity = std.time.timestamp(); gop.value_ptr.last_activity = platform_time.timestamp();
return true; return true;
}, },
.rejected_peer_limit, .rejected_total_limit => return false, .rejected_peer_limit, .rejected_total_limit => return false,
@@ -435,7 +441,7 @@ pub const PeerResponseTracker = struct {
} else { } else {
info.queued_bytes = 0; info.queued_bytes = 0;
} }
info.last_activity = std.time.timestamp(); info.last_activity = platform_time.timestamp();
// Clean up entry if peer has no more queued responses // Clean up entry if peer has no more queued responses
if (info.queued_count == 0) { if (info.queued_count == 0) {
@@ -454,7 +460,7 @@ pub const PeerResponseTracker = struct {
/// Clean up stale peer entries (peers with no activity for a while) /// Clean up stale peer entries (peers with no activity for a while)
pub fn cleanupStalePeers(self: *PeerResponseTracker) usize { pub fn cleanupStalePeers(self: *PeerResponseTracker) usize {
const now = std.time.timestamp(); const now = platform_time.timestamp();
var to_remove = std.ArrayList([32]u8).init(self.allocator); var to_remove = std.ArrayList([32]u8).init(self.allocator);
defer to_remove.deinit(); defer to_remove.deinit();
@@ -676,7 +682,7 @@ pub const PreSerializedPieceResponse = struct {
off += 1; off += 1;
// Message ID (4 bytes, big endian) // Message ID (4 bytes, big endian)
const msg_id = std.crypto.random.int(u32); const msg_id = platform_random.int(u32);
std.mem.writeInt(u32, result.header[off..][0..4], msg_id, .big); std.mem.writeInt(u32, result.header[off..][0..4], msg_id, .big);
off += 4; off += 4;
@@ -685,7 +691,7 @@ pub const PreSerializedPieceResponse = struct {
off += 2; off += 2;
// Timestamp (8 bytes, big endian) // Timestamp (8 bytes, big endian)
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
std.mem.writeInt(i64, result.header[off..][0..8], timestamp, .big); std.mem.writeInt(i64, result.header[off..][0..8], timestamp, .big);
off += 8; off += 8;
@@ -868,7 +874,7 @@ pub const FileSharingSession = struct {
const content_hash = try HashUtils.metadataHash(file_metadata); const content_hash = try HashUtils.metadataHash(file_metadata);
return FileSharingSession{ return FileSharingSession{
.session_id = std.crypto.random.int(u64), .session_id = platform_random.int(u64),
.file_metadata = file_metadata, .file_metadata = file_metadata,
.content_hash = content_hash, .content_hash = content_hash,
.download_manager = null, .download_manager = null,
@@ -876,8 +882,8 @@ pub const FileSharingSession = struct {
.transfer_protocol = TransferProtocol.init(allocator), .transfer_protocol = TransferProtocol.init(allocator),
.piece_pool = PiecePool.init(allocator), .piece_pool = PiecePool.init(allocator),
.status = .initializing, .status = .initializing,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.updated_at = std.time.timestamp(), .updated_at = platform_time.timestamp(),
.allocator = allocator, .allocator = allocator,
.response_tracker = null, // Initialized when upload starts .response_tracker = null, // Initialized when upload starts
.pending_piece_responses = .{}, .pending_piece_responses = .{},
@@ -1016,7 +1022,7 @@ pub const FileSharingSession = struct {
/// Update session timestamp /// Update session timestamp
pub fn update(self: *FileSharingSession) void { pub fn update(self: *FileSharingSession) void {
self.updated_at = std.time.timestamp(); self.updated_at = platform_time.timestamp();
} }
/// Check if session is active /// Check if session is active
@@ -1136,19 +1142,19 @@ pub const FileSharingManager = struct {
// DownloadManager.manager_mutex is only acquired while holding sessions_mutex, // DownloadManager.manager_mutex is only acquired while holding sessions_mutex,
// so it's implicitly ordered after sessions_mutex. // so it's implicitly ordered after sessions_mutex.
// ======================================================================== // ========================================================================
sessions_mutex: std.Thread.Mutex = .{}, sessions_mutex: Mutex = .{},
file_registry_mutex: std.Thread.Mutex = .{}, file_registry_mutex: Mutex = .{},
stats_mutex: std.Thread.Mutex = .{}, // Protects messages_sent/failed stats_mutex: Mutex = .{}, // Protects messages_sent/failed
/// THR-CRIT-2: Protects peer_reputation HashMap and all PeerReputation entry mutations. /// THR-CRIT-2: Protects peer_reputation HashMap and all PeerReputation entry mutations.
/// All HashMap access (.get, .getOrPut, .put) must be done while holding this mutex. /// All HashMap access (.get, .getOrPut, .put) must be done while holding this mutex.
/// Mutations to PeerReputation entries (recordBadPiece, recordGoodPiece) must be done /// Mutations to PeerReputation entries (recordBadPiece, recordGoodPiece) must be done
/// while holding this mutex. Read operations via .get() return a copy which is safe /// while holding this mutex. Read operations via .get() return a copy which is safe
/// to use outside the mutex. /// to use outside the mutex.
reputation_mutex: std.Thread.Mutex = .{}, reputation_mutex: Mutex = .{},
/// THR-H2 FIX: Protects runtime config modifications (bandwidth limits, strategies, features) /// THR-H2 FIX: Protects runtime config modifications (bandwidth limits, strategies, features)
/// Config is read during session operations and modified via updateBandwidthLimits, /// Config is read during session operations and modified via updateBandwidthLimits,
/// setSelectionStrategy, setFeatures. Mutex ensures atomic reads/writes. /// setSelectionStrategy, setFeatures. Mutex ensures atomic reads/writes.
config_mutex: std.Thread.Mutex = .{}, config_mutex: Mutex = .{},
// HIGH-5 FIX: Debug tracking for lock ordering verification // HIGH-5 FIX: Debug tracking for lock ordering verification
lock_order_debug: if (@import("builtin").mode == .Debug) LockOrderDebug else void = if (@import("builtin").mode == .Debug) .{} else {}, lock_order_debug: if (@import("builtin").mode == .Debug) LockOrderDebug else void = if (@import("builtin").mode == .Debug) .{} else {},
@@ -1161,7 +1167,7 @@ pub const FileSharingManager = struct {
threadlocal var tls_config_held: bool = false; threadlocal var tls_config_held: bool = false;
// Statistics for lock order violations (for monitoring) - global counter is fine // Statistics for lock order violations (for monitoring) - global counter is fine
violations_detected: std.atomic.Value(u64) = std.atomic.Value(u64).init(0), violations_detected: AtomicValue(u64) = AtomicValue(u64).init(0),
fn checkCanAcquireSessions(self: *LockOrderDebug) Error!void { fn checkCanAcquireSessions(self: *LockOrderDebug) Error!void {
// sessions_mutex can only be acquired if we either: // sessions_mutex can only be acquired if we either:
@@ -1238,7 +1244,7 @@ pub const FileSharingManager = struct {
.use_results_queue = true, .use_results_queue = true,
// PERF: Pre-allocate buffers for piece verification // PERF: Pre-allocate buffers for piece verification
.num_piece_buffers = config.buffer_pool_size, .num_piece_buffers = config.buffer_pool_size,
.piece_buffer_size = config.piece_size, .piece_buffer_size = @intCast(config.piece_size),
}) catch { }) catch {
// errdefer will handle destroy // errdefer will handle destroy
return Error.OutOfMemory; return Error.OutOfMemory;
@@ -1493,7 +1499,7 @@ pub const FileSharingManager = struct {
}; };
} }
session.status = .completed; session.status = .completed;
session.updated_at = std.time.timestamp(); session.updated_at = platform_time.timestamp();
std.log.info("Download completed! Session {d}: All {d} pieces verified (async), file_path={s}", .{ std.log.info("Download completed! Session {d}: All {d} pieces verified (async), file_path={s}", .{
session_id, session_id,
dm.state.piece_count, dm.state.piece_count,
@@ -1690,7 +1696,7 @@ pub const FileSharingManager = struct {
std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries}); std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries});
return Error.SystemError; return Error.SystemError;
} }
final_session_id = std.crypto.random.int(u64); final_session_id = platform_random.int(u64);
std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries}); std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries});
} }
session.session_id = final_session_id; session.session_id = final_session_id;
@@ -1855,7 +1861,7 @@ pub const FileSharingManager = struct {
std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries}); std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries});
return Error.SystemError; return Error.SystemError;
} }
final_session_id = std.crypto.random.int(u64); final_session_id = platform_random.int(u64);
std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries}); std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries});
} }
session.session_id = final_session_id; session.session_id = final_session_id;
@@ -1885,6 +1891,8 @@ pub const FileSharingManager = struct {
file_metadata: FileMetadata, file_metadata: FileMetadata,
output_path: []const u8, output_path: []const u8,
) Error!u64 { ) Error!u64 {
if (is_wasm) return Error.OperationNotSupported;
// SECURITY: Sanitize the filename from metadata to prevent path traversal // SECURITY: Sanitize the filename from metadata to prevent path traversal
// This is used for validation, not for determining the output path // This is used for validation, not for determining the output path
const sanitized_name = sanitizeFilename(file_metadata.name, self.allocator) catch return Error.OutOfMemory; const sanitized_name = sanitizeFilename(file_metadata.name, self.allocator) catch return Error.OutOfMemory;
@@ -1895,7 +1903,7 @@ pub const FileSharingManager = struct {
// If it's a file path, use it directly (user specified the exact destination) // If it's a file path, use it directly (user specified the exact destination)
const is_directory = blk: { const is_directory = blk: {
// Check if output_path exists and is a directory // Check if output_path exists and is a directory
const stat = std.fs.cwd().statFile(output_path) catch { const stat = filesystem.FileSystem.statFile(output_path) catch {
// Path doesn't exist - check if it ends with a path separator or has no extension // Path doesn't exist - check if it ends with a path separator or has no extension
const base = std.fs.path.basename(output_path); const base = std.fs.path.basename(output_path);
// If basename has no extension and doesn't look like a filename, treat as directory // If basename has no extension and doesn't look like a filename, treat as directory
@@ -2028,7 +2036,7 @@ pub const FileSharingManager = struct {
std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries}); std.log.err("HIGH-8: Session ID collision after {} retries - possible RNG failure", .{retries});
return Error.SystemError; return Error.SystemError;
} }
final_session_id = std.crypto.random.int(u64); final_session_id = platform_random.int(u64);
std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries}); std.log.warn("HIGH-8: Session ID collision detected, regenerating (attempt {})", .{retries});
} }
session.session_id = final_session_id; session.session_id = final_session_id;
@@ -2120,7 +2128,7 @@ pub const FileSharingManager = struct {
/// Process all active sessions /// Process all active sessions
pub fn processSessions(self: *FileSharingManager) Error!void { pub fn processSessions(self: *FileSharingManager) Error!void {
// TIMING: Track overall function time and phases // TIMING: Track overall function time and phases
const timer_start = std.time.nanoTimestamp(); const timer_start = platform_time.nanoTimestamp();
var phase1_time: i128 = 0; var phase1_time: i128 = 0;
var phase2_time: i128 = 0; var phase2_time: i128 = 0;
var phase3_time: i128 = 0; var phase3_time: i128 = 0;
@@ -2180,7 +2188,7 @@ pub const FileSharingManager = struct {
// CRIT-NEW-21 FIX: Track dropped messages due to OOM // CRIT-NEW-21 FIX: Track dropped messages due to OOM
var dropped_messages: usize = 0; var dropped_messages: usize = 0;
var total_messages: usize = 0; var total_messages: usize = 0;
const phase1_start = std.time.nanoTimestamp(); const phase1_start = platform_time.nanoTimestamp();
self.sessions_mutex.lock(); self.sessions_mutex.lock();
var it = self.sessions.valueIterator(); var it = self.sessions.valueIterator();
@@ -2314,8 +2322,8 @@ pub const FileSharingManager = struct {
} }
// TIMING: Phase 1 complete // TIMING: Phase 1 complete
phase1_time = std.time.nanoTimestamp() - phase1_start; phase1_time = platform_time.nanoTimestamp() - phase1_start;
const phase2_start = std.time.nanoTimestamp(); const phase2_start = platform_time.nanoTimestamp();
// PHASE 2: Send messages (NO lock held - prevents deadlock) // PHASE 2: Send messages (NO lock held - prevents deadlock)
for (messages_to_send.items) |msg| { for (messages_to_send.items) |msg| {
@@ -2326,7 +2334,7 @@ pub const FileSharingManager = struct {
.message_id = 0, .message_id = 0,
.peer_id = msg.peer_id_copy, .peer_id = msg.peer_id_copy,
.data = msg.data_copy, .data = msg.data_copy,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
std.log.debug("PHASE2: Sending message type={}", .{msg.message_type}); std.log.debug("PHASE2: Sending message type={}", .{msg.message_type});
// CRIT-NEW-19 FIX: Record swallowed error for tracking // CRIT-NEW-19 FIX: Record swallowed error for tracking
@@ -2371,8 +2379,8 @@ pub const FileSharingManager = struct {
} }
// TIMING: Phase 2 complete // TIMING: Phase 2 complete
phase2_time = std.time.nanoTimestamp() - phase2_start; phase2_time = platform_time.nanoTimestamp() - phase2_start;
const phase3_start = std.time.nanoTimestamp(); const phase3_start = platform_time.nanoTimestamp();
// ARCH-1 FIX: Process session download managers directly instead of the disconnected queue // ARCH-1 FIX: Process session download managers directly instead of the disconnected queue
// The queue held separate DownloadManagers that weren't linked to sessions // The queue held separate DownloadManagers that weren't linked to sessions
@@ -2539,8 +2547,8 @@ pub const FileSharingManager = struct {
} }
// TIMING: Phase 3 complete // TIMING: Phase 3 complete
phase3_time = std.time.nanoTimestamp() - phase3_start; phase3_time = platform_time.nanoTimestamp() - phase3_start;
const phase4_start = std.time.nanoTimestamp(); const phase4_start = platform_time.nanoTimestamp();
// ADAPTIVE: Record cycle statistics after processing all sessions // ADAPTIVE: Record cycle statistics after processing all sessions
// Record stuck downloads as partial timeouts - provides congestion signal // Record stuck downloads as partial timeouts - provides congestion signal
@@ -2586,7 +2594,7 @@ pub const FileSharingManager = struct {
} }
// TIMING: Phase 4 complete // TIMING: Phase 4 complete
phase4_time = std.time.nanoTimestamp() - phase4_start; phase4_time = platform_time.nanoTimestamp() - phase4_start;
// PHASE 5: Check for endgame broadcast trigger (outside lock to avoid deadlock) // PHASE 5: Check for endgame broadcast trigger (outside lock to avoid deadlock)
{ {
@@ -2613,7 +2621,7 @@ pub const FileSharingManager = struct {
self.cleanupCompletedSessions(); self.cleanupCompletedSessions();
// TIMING: Log timing breakdown only when significant (>10ms) // TIMING: Log timing breakdown only when significant (>10ms)
const total_time = std.time.nanoTimestamp() - timer_start; const total_time = platform_time.nanoTimestamp() - timer_start;
const total_ms = @as(f64, @floatFromInt(total_time)) / 1_000_000.0; const total_ms = @as(f64, @floatFromInt(total_time)) / 1_000_000.0;
if (total_ms > 10.0) { if (total_ms > 10.0) {
const p1_ms = @as(f64, @floatFromInt(phase1_time)) / 1_000_000.0; const p1_ms = @as(f64, @floatFromInt(phase1_time)) / 1_000_000.0;
@@ -2709,7 +2717,7 @@ pub const FileSharingManager = struct {
// CASCADE FIX: Keep completed sessions longer for cascade distribution // CASCADE FIX: Keep completed sessions longer for cascade distribution
// Previously 60 seconds was too short - peers couldn't serve pieces to slower downloaders // Previously 60 seconds was too short - peers couldn't serve pieces to slower downloaders
const grace_period_seconds: i64 = 3600; // Keep for 1 hour after completion const grace_period_seconds: i64 = 3600; // Keep for 1 hour after completion
const age = std.time.timestamp() - session.updated_at; const age = platform_time.timestamp() - session.updated_at;
if (session.status == .completed) { if (session.status == .completed) {
// Only remove completed sessions after grace period // Only remove completed sessions after grace period
if (age >= grace_period_seconds) { if (age >= grace_period_seconds) {
@@ -3231,16 +3239,16 @@ pub const FileSharingManager = struct {
/// THROUGHPUT FIX: Increased from 2GB to 4GB for high-throughput localhost testing. /// THROUGHPUT FIX: Increased from 2GB to 4GB for high-throughput localhost testing.
/// With 1MB pieces: 4GB / 1MB = 4096 messages /// With 1MB pieces: 4GB / 1MB = 4096 messages
/// This allows deep pipelines without triggering fair queue rejection. /// This allows deep pipelines without triggering fair queue rejection.
const MAX_QUEUED_RESPONSE_BYTES: usize = 4 * 1024 * 1024 * 1024; // 4GB max for high throughput const MAX_QUEUED_RESPONSE_BYTES: u64 = 4 * 1024 * 1024 * 1024; // 4GB max for high throughput
/// Calculate adaptive queue limit based on piece size /// Calculate adaptive queue limit based on piece size
fn calculateMaxQueuedResponses(piece_size: u64) usize { fn calculateMaxQueuedResponses(piece_size: u64) usize {
// Minimum 64 to ensure reasonable throughput, max 4000 for smaller pieces // Minimum 64 to ensure reasonable throughput, max 4000 for smaller pieces
// THROUGHPUT FIX: Increased limits to prevent silent request rejection // THROUGHPUT FIX: Increased limits to prevent silent request rejection
const piece_size_usize: usize = if (piece_size > std.math.maxInt(usize)) std.math.maxInt(usize) else @intCast(piece_size); if (piece_size == 0) return 4000;
if (piece_size_usize == 0) return 4000; const calculated: u64 = MAX_QUEUED_RESPONSE_BYTES / piece_size;
const calculated = MAX_QUEUED_RESPONSE_BYTES / piece_size_usize; const clamped = @min(@as(u64, 4000), @max(@as(u64, 64), calculated));
return @min(4000, @max(64, calculated)); return @intCast(clamped);
} }
/// Count only piece_data messages in the queue (the memory-heavy ones). /// Count only piece_data messages in the queue (the memory-heavy ones).
@@ -3458,7 +3466,7 @@ pub const FileSharingManager = struct {
.message_id = 0, .message_id = 0,
.peer_id = &peer_id, .peer_id = &peer_id,
.data = &reject_payload, .data = &reject_payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
_ = sender.sendMessage(reject_msg) catch {}; _ = sender.sendMessage(reject_msg) catch {};
} }
@@ -3640,7 +3648,7 @@ pub const FileSharingManager = struct {
// ASYNC VERIFICATION: Do disk write FIRST, then queue verification. // ASYNC VERIFICATION: Do disk write FIRST, then queue verification.
// This allows parallel verification while writes complete atomically via pwrite. // This allows parallel verification while writes complete atomically via pwrite.
// Using pwrite allows concurrent writes without holding mutex during I/O // Using pwrite allows concurrent writes without holding mutex during I/O
var write_file: std.fs.File = undefined; var write_file: filesystem.File = undefined;
var absolute_offset: u64 = undefined; var absolute_offset: u64 = undefined;
var write_file_path: []const u8 = undefined; var write_file_path: []const u8 = undefined;
{ {
@@ -3894,7 +3902,7 @@ pub const FileSharingManager = struct {
}; };
} }
session.status = .completed; session.status = .completed;
session.updated_at = std.time.timestamp(); session.updated_at = platform_time.timestamp();
std.log.info("Download completed! All {d} pieces verified", .{dm.state.piece_count}); std.log.info("Download completed! All {d} pieces verified", .{dm.state.piece_count});
// CASCADE FIX: Mark for full bitfield broadcast // CASCADE FIX: Mark for full bitfield broadcast
download_completed = true; download_completed = true;
@@ -4243,7 +4251,7 @@ pub const FileSharingManager = struct {
.offset = piece_offset, .offset = piece_offset,
.length = piece_size_u32, .length = piece_size_u32,
.priority = .normal, .priority = .normal,
.requested_at = std.time.timestamp(), .requested_at = platform_time.timestamp(),
// Use zero peer_id so a different peer will be selected // Use zero peer_id so a different peer will be selected
.peer_id = [_]u8{0} ** 32, .peer_id = [_]u8{0} ** 32,
}; };
@@ -4529,7 +4537,7 @@ pub const FileSharingManager = struct {
.offset = 0, .offset = 0,
.length = @intCast(dm.piece_size), .length = @intCast(dm.piece_size),
.priority = .high, .priority = .high,
.requested_at = std.time.timestamp(), .requested_at = platform_time.timestamp(),
}) catch continue; }) catch continue;
pieces_requeued += 1; pieces_requeued += 1;
@@ -4599,7 +4607,7 @@ pub const FileSharingManager = struct {
// content_hash already computed above for session lookup - reuse it // content_hash already computed above for session lookup - reuse it
var session = FileSharingSession{ var session = FileSharingSession{
.session_id = std.crypto.random.int(u64), .session_id = platform_random.int(u64),
.file_metadata = metadata, .file_metadata = metadata,
.content_hash = content_hash, .content_hash = content_hash,
.download_manager = null, .download_manager = null,
@@ -4607,8 +4615,8 @@ pub const FileSharingManager = struct {
.status = .ready, .status = .ready,
.transfer_protocol = transfer_mod.TransferProtocol.init(self.allocator), .transfer_protocol = transfer_mod.TransferProtocol.init(self.allocator),
.piece_pool = PiecePool.init(self.allocator), .piece_pool = PiecePool.init(self.allocator),
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.updated_at = std.time.timestamp(), .updated_at = platform_time.timestamp(),
.allocator = self.allocator, .allocator = self.allocator,
.response_tracker = null, // Download sessions don't need response tracking .response_tracker = null, // Download sessions don't need response tracking
.pending_piece_responses = .{}, // ZERO-COPY: Initialize empty .pending_piece_responses = .{}, // ZERO-COPY: Initialize empty
@@ -5021,12 +5029,12 @@ pub const SessionStats = struct {
/// Get session age in seconds /// Get session age in seconds
pub fn getAge(self: SessionStats) i64 { pub fn getAge(self: SessionStats) i64 {
return std.time.timestamp() - self.created_at; return platform_time.timestamp() - self.created_at;
} }
/// Get time since last update /// Get time since last update
pub fn getTimeSinceUpdate(self: SessionStats) i64 { pub fn getTimeSinceUpdate(self: SessionStats) i64 {
return std.time.timestamp() - self.updated_at; return platform_time.timestamp() - self.updated_at;
} }
/// Get formatted status string /// Get formatted status string
@@ -5204,7 +5212,7 @@ pub const FileSharingEvent = struct {
return FileSharingEvent{ return FileSharingEvent{
.event_type = event_type, .event_type = event_type,
.session_id = session_id, .session_id = session_id,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
.data = data, .data = data,
}; };
} }
@@ -5299,8 +5307,8 @@ test "session statistics formatting" {
.file_size = 1024 * 1024, .file_size = 1024 * 1024,
.piece_count = 10, .piece_count = 10,
.pieces_completed = 6, .pieces_completed = 6,
.created_at = std.time.timestamp() - 3600, // 1 hour ago .created_at = platform_time.timestamp() - 3600, // 1 hour ago
.updated_at = std.time.timestamp() - 300, // 5 minutes ago .updated_at = platform_time.timestamp() - 300, // 5 minutes ago
}; };
try testing.expectEqual(@as(i64, 3600), stats.getAge()); try testing.expectEqual(@as(i64, 3600), stats.getAge());
@@ -5544,7 +5552,7 @@ test "blacklisted peer cannot send pieces" {
manager.reputation_mutex.lock(); manager.reputation_mutex.lock();
var rep = PeerReputation.init(peer_id); var rep = PeerReputation.init(peer_id);
rep.bad_pieces = 3; rep.bad_pieces = 3;
rep.blacklisted_until = std.time.timestamp() + 1000; // Blacklisted for future rep.blacklisted_until = platform_time.timestamp() + 1000; // Blacklisted for future
try manager.peer_reputation.put(peer_id, rep); try manager.peer_reputation.put(peer_id, rep);
manager.reputation_mutex.unlock(); manager.reputation_mutex.unlock();
@@ -5776,7 +5784,7 @@ test "PeerReputation: reset clears all state" {
rep.bad_pieces = 5; rep.bad_pieces = 5;
rep.good_pieces = 10; rep.good_pieces = 10;
rep.blacklisted_until = std.time.timestamp() + 1000; rep.blacklisted_until = platform_time.timestamp() + 1000;
rep.reset(); rep.reset();
@@ -5833,7 +5841,7 @@ test "NetworkSender: sendMessage with mock callback" {
.message_id = 1, .message_id = 1,
.peer_id = &peer_id, .peer_id = &peer_id,
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = try sender.sendMessage(msg); const result = try sender.sendMessage(msg);
@@ -5857,7 +5865,7 @@ test "NetworkSender: sendMessage failure" {
.message_id = 1, .message_id = 1,
.peer_id = &peer_id, .peer_id = &peer_id,
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = try sender.sendMessage(msg); const result = try sender.sendMessage(msg);
@@ -5886,8 +5894,8 @@ test "FileSharingSession: status transitions" {
.size = 1024, .size = 1024,
.piece_count = 4, .piece_count = 4,
.piece_hashes = &[_]PieceHash{}, .piece_hashes = &[_]PieceHash{},
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.modified_at = std.time.timestamp(), .modified_at = platform_time.timestamp(),
}; };
var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator); var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator);
@@ -5912,8 +5920,8 @@ test "FileSharingSession: update timestamp" {
.size = 1024, .size = 1024,
.piece_count = 4, .piece_count = 4,
.piece_hashes = &[_]PieceHash{}, .piece_hashes = &[_]PieceHash{},
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.modified_at = std.time.timestamp(), .modified_at = platform_time.timestamp(),
}; };
var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator); var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator);
@@ -6178,8 +6186,8 @@ test "SessionStats: utility methods" {
.file_size = 1024, .file_size = 1024,
.piece_count = 4, .piece_count = 4,
.pieces_completed = 2, .pieces_completed = 2,
.created_at = std.time.timestamp() - 100, .created_at = platform_time.timestamp() - 100,
.updated_at = std.time.timestamp() - 50, .updated_at = platform_time.timestamp() - 50,
}; };
// Test getAge // Test getAge

View File

@@ -18,6 +18,7 @@
//! ``` //! ```
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const Allocator = std.mem.Allocator; const Allocator = std.mem.Allocator;
/// Error types for MockFS operations /// Error types for MockFS operations
@@ -47,8 +48,8 @@ pub const MockFile = struct {
return .{ return .{
.allocator = allocator, .allocator = allocator,
.data = &[_]u8{}, .data = &[_]u8{},
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.modified_at = std.time.timestamp(), .modified_at = platform_time.timestamp(),
}; };
} }
@@ -71,7 +72,7 @@ pub const MockFile = struct {
self.allocator.free(self.data); self.allocator.free(self.data);
} }
self.data = new_data; self.data = new_data;
self.modified_at = std.time.timestamp(); self.modified_at = platform_time.timestamp();
} }
pub fn resize(self: *MockFile, new_size: usize) !void { pub fn resize(self: *MockFile, new_size: usize) !void {
@@ -91,7 +92,7 @@ pub const MockFile = struct {
self.allocator.free(self.data); self.allocator.free(self.data);
} }
self.data = new_data; self.data = new_data;
self.modified_at = std.time.timestamp(); self.modified_at = platform_time.timestamp();
} }
}; };
@@ -149,7 +150,7 @@ pub const MockFileHandle = struct {
// Copy data // Copy data
@memcpy(file.data[self.position..][0..data.len], data); @memcpy(file.data[self.position..][0..data.len], data);
self.position += data.len; self.position += data.len;
file.modified_at = std.time.timestamp(); file.modified_at = platform_time.timestamp();
return data.len; return data.len;
} }
@@ -168,7 +169,7 @@ pub const MockFileHandle = struct {
// Copy data // Copy data
@memcpy(file.data[off..][0..data.len], data); @memcpy(file.data[off..][0..data.len], data);
file.modified_at = std.time.timestamp(); file.modified_at = platform_time.timestamp();
return data.len; return data.len;
} }

View File

@@ -5,6 +5,8 @@
//! file access by validating all file paths before operations. //! file access by validating all file paths before operations.
const std = @import("std"); const std = @import("std");
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const fs = std.fs; const fs = std.fs;
const mem = std.mem; const mem = std.mem;
@@ -61,6 +63,12 @@ pub const PathValidator = struct {
/// Returns the validated absolute path on success. /// Returns the validated absolute path on success.
/// Caller is responsible for freeing the returned path. /// Caller is responsible for freeing the returned path.
fn validatePath(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 { fn validatePath(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 {
// On WASM, no real filesystem — path validation is a simple pattern check + dupe
if (is_wasm) {
if (mem.indexOf(u8, path, "..") != null) return PathSecurityError.PathTraversal;
return allocator.dupe(u8, path) catch return error.OutOfMemory;
}
// 1. Check for path traversal patterns // 1. Check for path traversal patterns
if (mem.indexOf(u8, path, "..") != null) { if (mem.indexOf(u8, path, "..") != null) {
return PathSecurityError.PathTraversal; return PathSecurityError.PathTraversal;
@@ -379,6 +387,12 @@ pub const PathValidator = struct {
/// the path. For maximum security, use validateAndOpenFile() and keep the /// the path. For maximum security, use validateAndOpenFile() and keep the
/// file handle open until done using it. /// file handle open until done using it.
pub fn validateReadable(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 { pub fn validateReadable(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 {
// On WASM, no real filesystem — just validate patterns and return dupe
if (is_wasm) {
if (mem.indexOf(u8, path, "..") != null) return PathSecurityError.PathTraversal;
return allocator.dupe(u8, path) catch return error.OutOfMemory;
}
// Use TOCTOU-safe open to validate the file // Use TOCTOU-safe open to validate the file
const file = try self.validateAndOpenFile(path, allocator); const file = try self.validateAndOpenFile(path, allocator);
file.close(); file.close();
@@ -703,6 +717,12 @@ pub const PathValidator = struct {
/// could be modified by an attacker between validation and use. /// could be modified by an attacker between validation and use.
/// For security-critical operations, use validateAndCreateFile() instead. /// For security-critical operations, use validateAndCreateFile() instead.
pub fn validateWritable(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 { pub fn validateWritable(self: PathValidator, path: []const u8, allocator: mem.Allocator) ![]const u8 {
// On WASM, no real filesystem — just validate patterns and return dupe
if (is_wasm) {
if (!isPathSafe(path)) return PathSecurityError.PathTraversal;
return allocator.dupe(u8, path) catch return error.OutOfMemory;
}
// First, check for traversal patterns in the input // First, check for traversal patterns in the input
if (!isPathSafe(path)) { if (!isPathSafe(path)) {
return PathSecurityError.PathTraversal; return PathSecurityError.PathTraversal;
@@ -880,6 +900,13 @@ pub const PathValidator = struct {
/// Global default validator for general use /// Global default validator for general use
pub fn createDefaultValidator(allocator: mem.Allocator) !PathValidator { pub fn createDefaultValidator(allocator: mem.Allocator) !PathValidator {
if (is_wasm) {
// On WASM, no CWD — create a validator that accepts all paths
const allowed_dirs = try allocator.alloc([]const u8, 1);
allowed_dirs[0] = try allocator.dupe(u8, "/");
return PathValidator.init(allowed_dirs);
}
// Get current working directory as default allowed directory // Get current working directory as default allowed directory
const cwd = try fs.cwd().realpathAlloc(allocator, "."); const cwd = try fs.cwd().realpathAlloc(allocator, ".");

View File

@@ -4,6 +4,8 @@
//! Bandwidth-Delay Product (BDP) measurements. //! Bandwidth-Delay Product (BDP) measurements.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const Mutex = @import("sync").Mutex;
const core = @import("core"); const core = @import("core");
const Error = core.errors.Error; const Error = core.errors.Error;
@@ -69,7 +71,7 @@ pub const PeerMetrics = struct {
var metrics = PeerMetrics{ var metrics = PeerMetrics{
.peer_id = peer_id, .peer_id = peer_id,
.piece_size = piece_size, .piece_size = piece_size,
.last_bandwidth_calc_ns = std.time.nanoTimestamp(), .last_bandwidth_calc_ns = platform_time.nanoTimestamp(),
}; };
metrics.recalculateBdp(); metrics.recalculateBdp();
return metrics; return metrics;
@@ -77,13 +79,13 @@ pub const PeerMetrics = struct {
/// Record a request being sent (for RTT measurement) /// Record a request being sent (for RTT measurement)
pub fn recordRequestSent(self: *PeerMetrics) void { pub fn recordRequestSent(self: *PeerMetrics) void {
self.last_request_time_ns = std.time.nanoTimestamp(); self.last_request_time_ns = platform_time.nanoTimestamp();
self.current_pending += 1; self.current_pending += 1;
} }
/// Record a response received with timing for RTT calculation /// Record a response received with timing for RTT calculation
pub fn recordResponseReceived(self: *PeerMetrics, bytes: u64, success: bool) void { pub fn recordResponseReceived(self: *PeerMetrics, bytes: u64, success: bool) void {
const now = std.time.nanoTimestamp(); const now = platform_time.nanoTimestamp();
if (self.current_pending > 0) { if (self.current_pending > 0) {
self.current_pending -= 1; self.current_pending -= 1;
@@ -270,7 +272,7 @@ pub const PeerMetricsManager = struct {
/// Allocator /// Allocator
allocator: std.mem.Allocator, allocator: std.mem.Allocator,
/// Mutex for thread safety /// Mutex for thread safety
mutex: std.Thread.Mutex = .{}, mutex: Mutex = .{},
pub fn init(allocator: std.mem.Allocator, piece_size: u64) PeerMetricsManager { pub fn init(allocator: std.mem.Allocator, piece_size: u64) PeerMetricsManager {
return .{ return .{

View File

@@ -4,6 +4,7 @@
//! rarest-first, random, and sequential algorithms for optimal P2P distribution. //! rarest-first, random, and sequential algorithms for optimal P2P distribution.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const testing = std.testing; const testing = std.testing;
const mem = std.mem; const mem = std.mem;
const math = std.math; const math = std.math;
@@ -219,7 +220,7 @@ pub const PieceSelector = struct {
/// Mark piece as starting download /// Mark piece as starting download
pub fn startDownload(self: *PieceSelector, piece_index: u32) Error!void { pub fn startDownload(self: *PieceSelector, piece_index: u32) Error!void {
if (self.canStartDownload(piece_index)) { if (self.canStartDownload(piece_index)) {
try self.active_downloads.put(piece_index, std.time.timestamp()); try self.active_downloads.put(piece_index, platform_time.timestamp());
} else { } else {
return Error.RateLimited; return Error.RateLimited;
} }

View File

@@ -7,7 +7,9 @@
//! disk I/O operations by reusing buffers instead of allocating new ones. //! disk I/O operations by reusing buffers instead of allocating new ones.
const std = @import("std"); const std = @import("std");
const atomic = std.atomic; const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const mem = std.mem; const mem = std.mem;
const core = @import("core"); const core = @import("core");
@@ -57,14 +59,14 @@ pub const PieceBufferPool = struct {
/// Free list using indices (thread-safe via mutex) /// Free list using indices (thread-safe via mutex)
free_stack: std.ArrayList(usize), free_stack: std.ArrayList(usize),
mutex: std.Thread.Mutex, mutex: Mutex,
/// Statistics /// Statistics
acquired_count: atomic.Value(u64), acquired_count: AtomicValue(u64),
released_count: atomic.Value(u64), released_count: AtomicValue(u64),
fallback_count: atomic.Value(u64), fallback_count: AtomicValue(u64),
pool_hits: atomic.Value(u64), pool_hits: AtomicValue(u64),
pool_misses: atomic.Value(u64), pool_misses: AtomicValue(u64),
pub fn init(allocator: mem.Allocator, config: PieceBufferPoolConfig) Error!PieceBufferPool { pub fn init(allocator: mem.Allocator, config: PieceBufferPoolConfig) Error!PieceBufferPool {
// Allocate buffer pointer array // Allocate buffer pointer array
@@ -107,11 +109,11 @@ pub const PieceBufferPool = struct {
.buffers = buffers, .buffers = buffers,
.free_stack = free_stack, .free_stack = free_stack,
.mutex = .{}, .mutex = .{},
.acquired_count = atomic.Value(u64).init(0), .acquired_count = AtomicValue(u64).init(0),
.released_count = atomic.Value(u64).init(0), .released_count = AtomicValue(u64).init(0),
.fallback_count = atomic.Value(u64).init(0), .fallback_count = AtomicValue(u64).init(0),
.pool_hits = atomic.Value(u64).init(0), .pool_hits = AtomicValue(u64).init(0),
.pool_misses = atomic.Value(u64).init(0), .pool_misses = AtomicValue(u64).init(0),
}; };
} }

View File

@@ -21,9 +21,14 @@
//! ``` //! ```
const std = @import("std"); const std = @import("std");
const atomic = std.atomic; const platform_time = @import("platform").time;
const builtin = @import("builtin");
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const mem = std.mem; const mem = std.mem;
const Thread = std.Thread;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const core = @import("core"); const core = @import("core");
const Error = core.errors.Error; const Error = core.errors.Error;
@@ -96,24 +101,24 @@ pub const PiecePipeline = struct {
/// Task queue /// Task queue
task_queue: std.ArrayList(PieceTask), task_queue: std.ArrayList(PieceTask),
queue_mutex: Thread.Mutex, queue_mutex: Mutex,
queue_not_empty: Thread.Condition, queue_not_empty: if (is_wasm) void else std.Thread.Condition,
/// Worker threads /// Worker threads
workers: std.ArrayList(Thread), workers: if (is_wasm) void else std.ArrayList(std.Thread),
/// Shutdown flag /// Shutdown flag
shutdown: atomic.Value(bool), shutdown: AtomicValue(bool),
/// Callbacks for piece processing /// Callbacks for piece processing
callbacks: ?PipelineCallbacks, callbacks: ?PipelineCallbacks,
/// Statistics /// Statistics
tasks_queued: atomic.Value(u64), tasks_queued: AtomicValue(u64),
tasks_processed: atomic.Value(u64), tasks_processed: AtomicValue(u64),
tasks_failed: atomic.Value(u64), tasks_failed: AtomicValue(u64),
queue_full_count: atomic.Value(u64), queue_full_count: AtomicValue(u64),
total_queue_wait_ns: atomic.Value(u64), total_queue_wait_ns: AtomicValue(u64),
pub fn init(allocator: mem.Allocator, config: PiecePipelineConfig) PiecePipeline { pub fn init(allocator: mem.Allocator, config: PiecePipelineConfig) PiecePipeline {
return .{ return .{
@@ -121,15 +126,15 @@ pub const PiecePipeline = struct {
.config = config, .config = config,
.task_queue = .{}, .task_queue = .{},
.queue_mutex = .{}, .queue_mutex = .{},
.queue_not_empty = .{}, .queue_not_empty = if (is_wasm) {} else .{},
.workers = .{}, .workers = if (is_wasm) {} else .{},
.shutdown = atomic.Value(bool).init(false), .shutdown = AtomicValue(bool).init(false),
.callbacks = null, .callbacks = null,
.tasks_queued = atomic.Value(u64).init(0), .tasks_queued = AtomicValue(u64).init(0),
.tasks_processed = atomic.Value(u64).init(0), .tasks_processed = AtomicValue(u64).init(0),
.tasks_failed = atomic.Value(u64).init(0), .tasks_failed = AtomicValue(u64).init(0),
.queue_full_count = atomic.Value(u64).init(0), .queue_full_count = AtomicValue(u64).init(0),
.total_queue_wait_ns = atomic.Value(u64).init(0), .total_queue_wait_ns = AtomicValue(u64).init(0),
}; };
} }
@@ -141,7 +146,7 @@ pub const PiecePipeline = struct {
task.deinit(); task.deinit();
} }
self.task_queue.deinit(self.allocator); self.task_queue.deinit(self.allocator);
self.workers.deinit(self.allocator); if (!is_wasm) self.workers.deinit(self.allocator);
} }
/// Set the callbacks for piece processing /// Set the callbacks for piece processing
@@ -149,20 +154,22 @@ pub const PiecePipeline = struct {
self.callbacks = callbacks; self.callbacks = callbacks;
} }
/// Start worker threads /// Start worker threads (no-op on WASM — use processSynchronously instead)
pub fn start(self: *PiecePipeline) Error!void { pub fn start(self: *PiecePipeline) Error!void {
if (self.callbacks == null) { if (self.callbacks == null) {
return Error.InvalidState; return Error.InvalidState;
} }
if (is_wasm) return;
const num_workers = if (self.config.num_workers == 0) const num_workers = if (self.config.num_workers == 0)
@as(u32, @intCast(@max(1, Thread.getCpuCount() catch 4))) @as(u32, @intCast(@max(1, std.Thread.getCpuCount() catch 4)))
else else
self.config.num_workers; self.config.num_workers;
var i: u32 = 0; var i: u32 = 0;
while (i < num_workers) : (i += 1) { while (i < num_workers) : (i += 1) {
const thread = Thread.spawn(.{}, workerLoop, .{self}) catch { const thread = std.Thread.spawn(.{}, workerLoop, .{self}) catch {
return Error.InvalidState; return Error.InvalidState;
}; };
self.workers.append(self.allocator, thread) catch { self.workers.append(self.allocator, thread) catch {
@@ -171,8 +178,10 @@ pub const PiecePipeline = struct {
} }
} }
/// Stop all worker threads /// Stop all worker threads (no-op on WASM)
pub fn stop(self: *PiecePipeline) void { pub fn stop(self: *PiecePipeline) void {
if (is_wasm) return;
self.shutdown.store(true, .release); self.shutdown.store(true, .release);
// Wake up all workers // Wake up all workers
@@ -187,6 +196,42 @@ pub const PiecePipeline = struct {
self.workers.clearRetainingCapacity(); self.workers.clearRetainingCapacity();
} }
/// Process up to `max_tasks` pending pieces synchronously.
/// For WASM: call this from the update loop since threads are unavailable.
/// On native: this can also be used for single-threaded operation.
pub fn processSynchronously(self: *PiecePipeline, max_tasks: u32) void {
const cb = self.callbacks orelse return;
var processed: u32 = 0;
while (processed < max_tasks) : (processed += 1) {
// Dequeue a task
var task: PieceTask = undefined;
{
self.queue_mutex.lock();
defer self.queue_mutex.unlock();
if (self.task_queue.items.len == 0) break;
task = self.task_queue.orderedRemove(0);
}
defer task.deinit();
// Track queue wait time
const wait_ns: u64 = @intCast(@max(0, platform_time.nanoTimestamp() - task.queued_at));
_ = self.total_queue_wait_ns.fetchAdd(wait_ns, .monotonic);
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);
}
}
/// Queue a piece for processing (non-blocking for caller) /// Queue a piece for processing (non-blocking for caller)
/// The data is COPIED - caller can free their copy after this returns /// The data is COPIED - caller can free their copy after this returns
pub fn queuePiece( pub fn queuePiece(
@@ -222,14 +267,14 @@ pub const PiecePipeline = struct {
.offset = offset, .offset = offset,
.data = data_copy, .data = data_copy,
.allocator = self.allocator, .allocator = self.allocator,
.queued_at = std.time.nanoTimestamp(), .queued_at = platform_time.nanoTimestamp(),
}) catch { }) catch {
self.allocator.free(data_copy); self.allocator.free(data_copy);
return Error.OutOfMemory; return Error.OutOfMemory;
}; };
_ = self.tasks_queued.fetchAdd(1, .monotonic); _ = self.tasks_queued.fetchAdd(1, .monotonic);
self.queue_not_empty.signal(); if (!is_wasm) self.queue_not_empty.signal();
} }
/// Get current queue depth /// Get current queue depth
@@ -287,7 +332,7 @@ pub const PiecePipeline = struct {
defer t.deinit(); defer t.deinit();
// Track queue wait time // Track queue wait time
const wait_ns: u64 = @intCast(@max(0, std.time.nanoTimestamp() - t.queued_at)); const wait_ns: u64 = @intCast(@max(0, platform_time.nanoTimestamp() - t.queued_at));
_ = self.total_queue_wait_ns.fetchAdd(wait_ns, .monotonic); _ = self.total_queue_wait_ns.fetchAdd(wait_ns, .monotonic);
// Process the piece via callback // Process the piece via callback
@@ -364,7 +409,7 @@ test "piece pipeline basic operations" {
const TestContext = struct { const TestContext = struct {
processed_count: u32 = 0, processed_count: u32 = 0,
mutex: Thread.Mutex = .{}, mutex: Mutex = .{},
}; };
var ctx = TestContext{}; var ctx = TestContext{};

View File

@@ -4,6 +4,9 @@
//! message exchange, and coordination between download and upload operations. //! message exchange, and coordination between download and upload operations.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const platform_random = @import("platform").random;
const AtomicValue = @import("sync").AtomicValue;
const testing = std.testing; const testing = std.testing;
const mem = std.mem; const mem = std.mem;
const fmt = std.fmt; const fmt = std.fmt;
@@ -132,7 +135,7 @@ pub const PreSerializedPieceData = struct {
offset += 1; offset += 1;
// Message ID (4 bytes, big endian) // Message ID (4 bytes, big endian)
const msg_id = std.crypto.random.int(u32); const msg_id = platform_random.int(u32);
@memcpy(result.header[offset..][0..4], &std.mem.toBytes(std.mem.nativeToBig(u32, msg_id))); @memcpy(result.header[offset..][0..4], &std.mem.toBytes(std.mem.nativeToBig(u32, msg_id)));
offset += 4; offset += 4;
@@ -142,7 +145,7 @@ pub const PreSerializedPieceData = struct {
offset += 2; offset += 2;
// Timestamp (8 bytes, big endian) // Timestamp (8 bytes, big endian)
const timestamp = std.time.timestamp(); const timestamp = platform_time.timestamp();
@memcpy(result.header[offset..][0..8], &std.mem.toBytes(std.mem.nativeToBig(i64, timestamp))); @memcpy(result.header[offset..][0..8], &std.mem.toBytes(std.mem.nativeToBig(i64, timestamp)));
offset += 8; offset += 8;
@@ -345,7 +348,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const payload = fmt.allocPrint(allocator, "HANDshake {s} {s}", .{ peer_id, client_id }) catch { const payload = fmt.allocPrint(allocator, "HANDshake {s} {s}", .{ peer_id, client_id }) catch {
@@ -355,16 +358,16 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
return TransferMessage{ return TransferMessage{
.message_type = .handshake, .message_type = .handshake,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -376,7 +379,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const payload = allocator.alloc(u8, 32) catch { const payload = allocator.alloc(u8, 32) catch {
@@ -386,17 +389,17 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@memcpy(payload, &file_hash); @memcpy(payload, &file_hash);
return TransferMessage{ return TransferMessage{
.message_type = .metadata_request, .message_type = .metadata_request,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -409,7 +412,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
// Serialize metadata: name_len(2) + name + size(8) + piece_count(4) + created_at(8) + modified_at(8) + piece_hashes // Serialize metadata: name_len(2) + name + size(8) + piece_count(4) + created_at(8) + modified_at(8) + piece_hashes
@@ -423,7 +426,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -436,7 +439,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -475,10 +478,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .metadata_response, .message_type = .metadata_response,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -564,7 +567,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
// Payload format: content_hash(32) + piece_index(4) + offset(4) = 40 bytes // Payload format: content_hash(32) + piece_index(4) + offset(4) = 40 bytes
@@ -575,7 +578,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -588,10 +591,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .piece_request, .message_type = .piece_request,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -612,7 +615,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -621,7 +624,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
// Payload: content_hash(32) + count(2) + indices(4 * count) // Payload: content_hash(32) + count(2) + indices(4 * count)
@@ -633,7 +636,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -647,10 +650,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .batch_piece_request, .message_type = .batch_piece_request,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -686,7 +689,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const payload = allocator.alloc(u8, 9) catch { const payload = allocator.alloc(u8, 9) catch {
@@ -696,7 +699,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -706,10 +709,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .piece_response, .message_type = .piece_response,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -724,7 +727,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
// Combine piece index, data, and hash // Combine piece index, data, and hash
@@ -738,7 +741,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -753,10 +756,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .piece_data, .message_type = .piece_data,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -769,7 +772,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const payload = allocator.alloc(u8, 8) catch { const payload = allocator.alloc(u8, 8) catch {
@@ -779,7 +782,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -788,10 +791,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .cancel_request, .message_type = .cancel_request,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -805,7 +808,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
// Calculate bitfield size: ceil(piece_count / 8) // Calculate bitfield size: ceil(piece_count / 8)
@@ -819,7 +822,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -839,10 +842,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .bitfield, .message_type = .bitfield,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -855,7 +858,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const bitfield_bytes = (piece_count + 7) / 8; const bitfield_bytes = (piece_count + 7) / 8;
@@ -868,7 +871,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -886,10 +889,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .bitfield, .message_type = .bitfield,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -903,7 +906,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
// Format: content_hash(32) + piece_index(4) // Format: content_hash(32) + piece_index(4)
@@ -914,7 +917,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
@@ -923,10 +926,10 @@ pub const TransferMessage = struct {
return TransferMessage{ return TransferMessage{
.message_type = .have, .message_type = .have,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = payload, .data = payload,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
@@ -982,7 +985,7 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, // Empty slice to avoid freeing invalid memory .peer_id = &[_]u8{}, // Empty slice to avoid freeing invalid memory
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const owned_data = allocator.dupe(u8, error_text) catch { const owned_data = allocator.dupe(u8, error_text) catch {
@@ -992,22 +995,22 @@ pub const TransferMessage = struct {
.message_id = 0, .message_id = 0,
.peer_id = &[_]u8{}, .peer_id = &[_]u8{},
.data = &[_]u8{}, .data = &[_]u8{},
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
}; };
return TransferMessage{ return TransferMessage{
.message_type = .err, .message_type = .err,
.message_id = std.crypto.random.int(u32), .message_id = platform_random.int(u32),
.peer_id = owned_peer_id, .peer_id = owned_peer_id,
.data = owned_data, .data = owned_data,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
} }
/// Check if message has expired /// Check if message has expired
pub fn isExpired(self: TransferMessage, timeout_seconds: i64) bool { pub fn isExpired(self: TransferMessage, timeout_seconds: i64) bool {
return std.time.timestamp() - self.timestamp > timeout_seconds; return platform_time.timestamp() - self.timestamp > timeout_seconds;
} }
}; };
@@ -1060,7 +1063,7 @@ pub const TransferSession = struct {
const content_hash = HashUtils.contentHash(file_metadata.piece_hashes) catch return Error.HashComputationFailed; const content_hash = HashUtils.contentHash(file_metadata.piece_hashes) catch return Error.HashComputationFailed;
return TransferSession{ return TransferSession{
.session_id = std.crypto.random.int(u64), .session_id = platform_random.int(u64),
.peer_id = peer_id, .peer_id = peer_id,
.file_metadata = file_metadata, .file_metadata = file_metadata,
.content_hash = content_hash, .content_hash = content_hash,
@@ -1069,8 +1072,8 @@ pub const TransferSession = struct {
.peer_capabilities = PeerCapabilities.init(allocator), .peer_capabilities = PeerCapabilities.init(allocator),
.progress_tracker = ProgressTracker.init(file_metadata.size), .progress_tracker = ProgressTracker.init(file_metadata.size),
.rate_limiter = RateLimiter.init(), .rate_limiter = RateLimiter.init(),
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.last_activity = std.time.timestamp(), .last_activity = platform_time.timestamp(),
// IMP-M2 FIX: Initialize received piece hashes map // IMP-M2 FIX: Initialize received piece hashes map
.received_piece_hashes = std.AutoHashMap(u32, PieceHash).init(allocator), .received_piece_hashes = std.AutoHashMap(u32, PieceHash).init(allocator),
.allocator = allocator, .allocator = allocator,
@@ -1085,12 +1088,12 @@ pub const TransferSession = struct {
/// Update last activity timestamp /// Update last activity timestamp
pub fn updateActivity(self: *TransferSession) void { pub fn updateActivity(self: *TransferSession) void {
self.last_activity = std.time.timestamp(); self.last_activity = platform_time.timestamp();
} }
/// Check if session is active /// Check if session is active
pub fn isActive(self: *TransferSession, timeout_seconds: i64) bool { pub fn isActive(self: *TransferSession, timeout_seconds: i64) bool {
return std.time.timestamp() - self.last_activity < timeout_seconds; return platform_time.timestamp() - self.last_activity < timeout_seconds;
} }
/// Get transfer progress /// Get transfer progress
@@ -1294,8 +1297,8 @@ pub const TransferProtocol = struct {
.size = 0, .size = 0,
.piece_count = 0, .piece_count = 0,
.piece_hashes = empty_hashes, .piece_hashes = empty_hashes,
.created_at = std.time.timestamp(), .created_at = platform_time.timestamp(),
.modified_at = std.time.timestamp(), .modified_at = platform_time.timestamp(),
}; };
const session = TransferSession.create(peer_id, metadata, self.allocator) catch return Error.OutOfMemory; const session = TransferSession.create(peer_id, metadata, self.allocator) catch return Error.OutOfMemory;
@@ -2135,16 +2138,16 @@ pub const TransferStats = struct {
pub const RateLimiter = struct { pub const RateLimiter = struct {
max_bandwidth_bps: u64, max_bandwidth_bps: u64,
max_concurrent_transfers: usize, max_concurrent_transfers: usize,
current_bandwidth: std.atomic.Value(u64), current_bandwidth: AtomicValue(u64),
active_transfers: std.atomic.Value(usize), active_transfers: AtomicValue(usize),
/// Initialize with custom bandwidth limits /// Initialize with custom bandwidth limits
pub fn initWithLimits(max_bandwidth_bps: u64, max_concurrent_transfers: usize) RateLimiter { pub fn initWithLimits(max_bandwidth_bps: u64, max_concurrent_transfers: usize) RateLimiter {
return RateLimiter{ return RateLimiter{
.max_bandwidth_bps = max_bandwidth_bps, .max_bandwidth_bps = max_bandwidth_bps,
.max_concurrent_transfers = max_concurrent_transfers, .max_concurrent_transfers = max_concurrent_transfers,
.current_bandwidth = std.atomic.Value(u64).init(0), .current_bandwidth = AtomicValue(u64).init(0),
.active_transfers = std.atomic.Value(usize).init(0), .active_transfers = AtomicValue(usize).init(0),
}; };
} }
@@ -2229,18 +2232,18 @@ pub const RateLimiter = struct {
/// Progress tracker for transfers /// Progress tracker for transfers
pub const ProgressTracker = struct { pub const ProgressTracker = struct {
total_bytes: u64, total_bytes: u64,
downloaded_bytes: std.atomic.Value(u64), downloaded_bytes: AtomicValue(u64),
uploaded_bytes: std.atomic.Value(u64), uploaded_bytes: AtomicValue(u64),
start_time: i64, start_time: i64,
last_update: std.atomic.Value(i64), last_update: AtomicValue(i64),
pub fn init(total_bytes: u64) ProgressTracker { pub fn init(total_bytes: u64) ProgressTracker {
return ProgressTracker{ return ProgressTracker{
.total_bytes = total_bytes, .total_bytes = total_bytes,
.downloaded_bytes = std.atomic.Value(u64).init(0), .downloaded_bytes = AtomicValue(u64).init(0),
.uploaded_bytes = std.atomic.Value(u64).init(0), .uploaded_bytes = AtomicValue(u64).init(0),
.start_time = std.time.timestamp(), .start_time = platform_time.timestamp(),
.last_update = std.atomic.Value(i64).init(std.time.timestamp()), .last_update = AtomicValue(i64).init(platform_time.timestamp()),
}; };
} }
@@ -2248,14 +2251,14 @@ pub const ProgressTracker = struct {
/// RACE CONDITION FIX: Use fetchAdd instead of load-store pattern /// RACE CONDITION FIX: Use fetchAdd instead of load-store pattern
pub fn updateDownload(self: *ProgressTracker, bytes: u64) void { pub fn updateDownload(self: *ProgressTracker, bytes: u64) void {
_ = self.downloaded_bytes.fetchAdd(bytes, .monotonic); _ = self.downloaded_bytes.fetchAdd(bytes, .monotonic);
self.last_update.store(std.time.timestamp(), .monotonic); self.last_update.store(platform_time.timestamp(), .monotonic);
} }
/// Update uploaded bytes /// Update uploaded bytes
/// RACE CONDITION FIX: Use fetchAdd instead of load-store pattern /// RACE CONDITION FIX: Use fetchAdd instead of load-store pattern
pub fn updateUpload(self: *ProgressTracker, bytes: u64) void { pub fn updateUpload(self: *ProgressTracker, bytes: u64) void {
_ = self.uploaded_bytes.fetchAdd(bytes, .monotonic); _ = self.uploaded_bytes.fetchAdd(bytes, .monotonic);
self.last_update.store(std.time.timestamp(), .monotonic); self.last_update.store(platform_time.timestamp(), .monotonic);
} }
/// Add uploaded bytes (alias for updateUpload) /// Add uploaded bytes (alias for updateUpload)
@@ -2279,7 +2282,7 @@ pub const ProgressTracker = struct {
/// Get download speed in bytes per second /// Get download speed in bytes per second
pub fn getDownloadSpeed(self: *ProgressTracker) f32 { pub fn getDownloadSpeed(self: *ProgressTracker) f32 {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const elapsed = now - self.start_time; const elapsed = now - self.start_time;
if (elapsed <= 0) return 0.0; if (elapsed <= 0) return 0.0;
@@ -2289,7 +2292,7 @@ pub const ProgressTracker = struct {
/// Get upload speed in bytes per second /// Get upload speed in bytes per second
pub fn getUploadSpeed(self: *ProgressTracker) f32 { pub fn getUploadSpeed(self: *ProgressTracker) f32 {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const elapsed = now - self.start_time; const elapsed = now - self.start_time;
if (elapsed <= 0) return 0.0; if (elapsed <= 0) return 0.0;
@@ -2313,7 +2316,7 @@ pub const ProgressTracker = struct {
/// Check if transfer is stalled /// Check if transfer is stalled
pub fn isStalled(self: *ProgressTracker, timeout_seconds: i64) bool { pub fn isStalled(self: *ProgressTracker, timeout_seconds: i64) bool {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const last_update = self.last_update.load(.monotonic); const last_update = self.last_update.load(.monotonic);
return now - last_update > timeout_seconds; return now - last_update > timeout_seconds;
} }
@@ -2417,14 +2420,14 @@ test "transfer message expiration" {
.message_id = 12345, .message_id = 12345,
.peer_id = "test_peer", .peer_id = "test_peer",
.data = "test data", .data = "test data",
.timestamp = std.time.timestamp() - 120, // 2 minutes ago .timestamp = platform_time.timestamp() - 120, // 2 minutes ago
}; };
// Message should be expired (60 second timeout) // Message should be expired (60 second timeout)
try testing.expect(message.isExpired(60)); try testing.expect(message.isExpired(60));
// Fresh message should not be expired // Fresh message should not be expired
message.timestamp = std.time.timestamp(); message.timestamp = platform_time.timestamp();
try testing.expect(!message.isExpired(60)); try testing.expect(!message.isExpired(60));
} }
@@ -2771,7 +2774,7 @@ test "ProgressTracker isStalled" {
try testing.expect(!tracker.isStalled(60)); try testing.expect(!tracker.isStalled(60));
// Manually set old last_update // Manually set old last_update
tracker.last_update.store(std.time.timestamp() - 120, .monotonic); tracker.last_update.store(platform_time.timestamp() - 120, .monotonic);
// Should be stalled now (120s > 60s timeout) // Should be stalled now (120s > 60s timeout)
try testing.expect(tracker.isStalled(60)); try testing.expect(tracker.isStalled(60));
@@ -2781,7 +2784,7 @@ test "ProgressTracker getEstimatedDownloadTimeRemaining" {
var tracker = ProgressTracker.init(1000); var tracker = ProgressTracker.init(1000);
// No progress yet - returns 0 (progress is 0.0, so boundary case) // No progress yet - returns 0 (progress is 0.0, so boundary case)
tracker.start_time = std.time.timestamp() - 10; tracker.start_time = platform_time.timestamp() - 10;
try testing.expectEqual(@as(i64, 0), tracker.getEstimatedDownloadTimeRemaining()); try testing.expectEqual(@as(i64, 0), tracker.getEstimatedDownloadTimeRemaining());
// With some progress // With some progress
@@ -2907,7 +2910,7 @@ test "TransferProtocol handleError" {
.message_id = 1, .message_id = 1,
.peer_id = "peer1", .peer_id = "peer1",
.data = "test error", .data = "test error",
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
try protocol.handleMessage(error_msg); try protocol.handleMessage(error_msg);
@@ -2930,7 +2933,7 @@ test "TransferProtocol handleBandwidthUpdate" {
.message_id = 1, .message_id = 1,
.peer_id = "peer1", .peer_id = "peer1",
.data = "", .data = "",
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
// Should succeed since session exists (even without upload manager) // Should succeed since session exists (even without upload manager)
@@ -2957,7 +2960,7 @@ test "TransferProtocol handleTransferComplete" {
.message_id = 1, .message_id = 1,
.peer_id = "peer1", .peer_id = "peer1",
.data = "", .data = "",
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
try protocol.handleMessage(complete_msg); try protocol.handleMessage(complete_msg);
@@ -3059,7 +3062,7 @@ test "TransferProtocol popMessagesFair prioritizes requests" {
.message_id = 1, .message_id = 1,
.peer_id = response_peer_id, .peer_id = response_peer_id,
.data = response_data, .data = response_data,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
try protocol.pending_responses.append(allocator, response_msg); try protocol.pending_responses.append(allocator, response_msg);
@@ -3071,7 +3074,7 @@ test "TransferProtocol popMessagesFair prioritizes requests" {
.message_id = 2, .message_id = 2,
.peer_id = request_peer_id, .peer_id = request_peer_id,
.data = request_data, .data = request_data,
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
try protocol.pending_requests.append(allocator, request_msg); try protocol.pending_requests.append(allocator, request_msg);
@@ -3123,7 +3126,7 @@ test "TransferProtocol handleHandshake invalid format" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "short", .data = "short",
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(short_msg); const result = protocol.handleMessage(short_msg);
@@ -3140,7 +3143,7 @@ test "TransferProtocol handleHandshake invalid prefix" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "INVALID peer1 client1", .data = "INVALID peer1 client1",
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(bad_msg); const result = protocol.handleMessage(bad_msg);
@@ -3158,7 +3161,7 @@ test "TransferProtocol handleHandshake invalid characters" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "HANDshake peer@invalid client1", .data = "HANDshake peer@invalid client1",
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(bad_msg); const result = protocol.handleMessage(bad_msg);
@@ -3175,7 +3178,7 @@ test "TransferProtocol handleCancelRequest invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "short", // Too short .data = "short", // Too short
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(cancel_msg); const result = protocol.handleMessage(cancel_msg);
@@ -3192,7 +3195,7 @@ test "TransferProtocol handlePieceRequest invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "short", // Too short (needs 16 bytes) .data = "short", // Too short (needs 16 bytes)
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(piece_req); const result = protocol.handleMessage(piece_req);
@@ -3209,7 +3212,7 @@ test "TransferProtocol handlePieceResponse invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "short", // Too short (needs 9 bytes) .data = "short", // Too short (needs 9 bytes)
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(piece_resp); const result = protocol.handleMessage(piece_resp);
@@ -3226,7 +3229,7 @@ test "TransferProtocol handlePieceData invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "short", // Too short (needs 36 bytes minimum) .data = "short", // Too short (needs 36 bytes minimum)
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(piece_data_msg); const result = protocol.handleMessage(piece_data_msg);
@@ -3243,7 +3246,7 @@ test "TransferProtocol handlePieceHash invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "short", // Too short (needs 36 bytes) .data = "short", // Too short (needs 36 bytes)
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(piece_hash_msg); const result = protocol.handleMessage(piece_hash_msg);
@@ -3260,7 +3263,7 @@ test "TransferProtocol handleUploadRequest invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "short", // Too short (needs 48 bytes) .data = "short", // Too short (needs 48 bytes)
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(upload_req); const result = protocol.handleMessage(upload_req);
@@ -3277,7 +3280,7 @@ test "TransferProtocol handleBitfield invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "ab", // Too short .data = "ab", // Too short
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(bitfield_msg); const result = protocol.handleMessage(bitfield_msg);
@@ -3294,7 +3297,7 @@ test "TransferProtocol handleHave invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "ab", // Too short (needs 4 bytes) .data = "ab", // Too short (needs 4 bytes)
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(have_msg); const result = protocol.handleMessage(have_msg);
@@ -3311,7 +3314,7 @@ test "TransferProtocol handleBatchPieceRequest invalid data" {
.message_id = 1, .message_id = 1,
.peer_id = "peer", .peer_id = "peer",
.data = "short", // Too short .data = "short", // Too short
.timestamp = std.time.timestamp(), .timestamp = platform_time.timestamp(),
}; };
const result = protocol.handleMessage(batch_req); const result = protocol.handleMessage(batch_req);

View File

@@ -4,9 +4,14 @@
//! bandwidth allocation, and upload rate limiting. //! bandwidth allocation, and upload rate limiting.
const std = @import("std"); const std = @import("std");
const platform_time = @import("platform").time;
const builtin = @import("builtin");
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const testing = std.testing; const testing = std.testing;
const mem = std.mem; const mem = std.mem;
const atomic = std.atomic;
const fmt = std.fmt; const fmt = std.fmt;
const core = @import("core"); const core = @import("core");
@@ -14,6 +19,8 @@ const Error = core.errors.Error;
const hash_mod = @import("hash.zig"); const hash_mod = @import("hash.zig");
const PieceHash = hash_mod.PieceHash; const PieceHash = hash_mod.PieceHash;
const HashUtils = hash_mod.HashUtils; const HashUtils = hash_mod.HashUtils;
const filesystem = @import("filesystem.zig");
const FileSystem = filesystem.FileSystem;
const file_mod = @import("file.zig"); const file_mod = @import("file.zig");
const FileChunker = file_mod.FileChunker; const FileChunker = file_mod.FileChunker;
const MappedFile = file_mod.MappedFile; const MappedFile = file_mod.MappedFile;
@@ -97,7 +104,7 @@ pub const UploadRequest = struct {
.offset = offset, .offset = offset,
.length = length, .length = length,
.peer_id = peer_id_owned, .peer_id = peer_id_owned,
.requested_at = std.time.timestamp(), .requested_at = platform_time.timestamp(),
.priority = priority, .priority = priority,
.request_id = 0, .request_id = 0,
.file_hash = [_]u8{0} ** 32, .file_hash = [_]u8{0} ** 32,
@@ -123,7 +130,7 @@ pub const UploadRequest = struct {
.offset = offset, .offset = offset,
.length = length, .length = length,
.peer_id = peer_id_owned, .peer_id = peer_id_owned,
.requested_at = std.time.timestamp(), .requested_at = platform_time.timestamp(),
.priority = priority, .priority = priority,
.request_id = request_id, .request_id = request_id,
.file_hash = file_hash, .file_hash = file_hash,
@@ -132,7 +139,7 @@ pub const UploadRequest = struct {
/// Check if request has expired /// Check if request has expired
pub fn isExpired(self: UploadRequest, timeout_seconds: i64) bool { pub fn isExpired(self: UploadRequest, timeout_seconds: i64) bool {
return std.time.timestamp() - self.requested_at > timeout_seconds; return platform_time.timestamp() - self.requested_at > timeout_seconds;
} }
/// Get request score for prioritization /// Get request score for prioritization
@@ -143,7 +150,7 @@ pub const UploadRequest = struct {
score += @as(i32, @intFromEnum(self.priority)) * 100; score += @as(i32, @intFromEnum(self.priority)) * 100;
// Time waited boost (older requests get higher score) // Time waited boost (older requests get higher score)
const time_waited = std.time.timestamp() - self.requested_at; const time_waited = platform_time.timestamp() - self.requested_at;
score += @as(i32, @intCast(@min(time_waited, 300))); // Max 5 minutes boost score += @as(i32, @intCast(@min(time_waited, 300))); // Max 5 minutes boost
return score; return score;
@@ -161,26 +168,26 @@ pub const UploadRequest = struct {
/// This is acceptable for statistics tracking where eventual consistency is /// This is acceptable for statistics tracking where eventual consistency is
/// sufficient. If strict transactional semantics are needed, use a mutex. /// sufficient. If strict transactional semantics are needed, use a mutex.
pub const UploadState = struct { pub const UploadState = struct {
total_uploaded: atomic.Value(u64), total_uploaded: AtomicValue(u64),
active_uploads: atomic.Value(u32), active_uploads: AtomicValue(u32),
completed_uploads: atomic.Value(u32), completed_uploads: AtomicValue(u32),
failed_uploads: atomic.Value(u32), failed_uploads: AtomicValue(u32),
/// IMP-M4 FIX: Track cancelled uploads separately /// IMP-M4 FIX: Track cancelled uploads separately
cancelled_count: atomic.Value(u32), cancelled_count: AtomicValue(u32),
start_time: i64, start_time: i64,
upload_bandwidth: atomic.Value(u64), // Current bandwidth usage upload_bandwidth: AtomicValue(u64), // Current bandwidth usage
max_bandwidth: u64, // Maximum allowed bandwidth max_bandwidth: u64, // Maximum allowed bandwidth
pub fn init(max_bandwidth: u64) UploadState { pub fn init(max_bandwidth: u64) UploadState {
return UploadState{ return UploadState{
.total_uploaded = atomic.Value(u64).init(0), .total_uploaded = AtomicValue(u64).init(0),
.active_uploads = atomic.Value(u32).init(0), .active_uploads = AtomicValue(u32).init(0),
.completed_uploads = atomic.Value(u32).init(0), .completed_uploads = AtomicValue(u32).init(0),
.failed_uploads = atomic.Value(u32).init(0), .failed_uploads = AtomicValue(u32).init(0),
// IMP-M4 FIX: Initialize cancelled counter // IMP-M4 FIX: Initialize cancelled counter
.cancelled_count = atomic.Value(u32).init(0), .cancelled_count = AtomicValue(u32).init(0),
.start_time = std.time.timestamp(), .start_time = platform_time.timestamp(),
.upload_bandwidth = atomic.Value(u64).init(0), .upload_bandwidth = AtomicValue(u64).init(0),
.max_bandwidth = max_bandwidth, .max_bandwidth = max_bandwidth,
}; };
} }
@@ -242,7 +249,7 @@ pub const UploadState = struct {
/// Get upload speed (bytes per second) /// Get upload speed (bytes per second)
/// Uses .acquire to ensure we see latest upload counts. /// Uses .acquire to ensure we see latest upload counts.
pub fn getUploadSpeed(self: *UploadState) f32 { pub fn getUploadSpeed(self: *UploadState) f32 {
const elapsed = std.time.timestamp() - self.start_time; const elapsed = platform_time.timestamp() - self.start_time;
if (elapsed <= 0) return 0.0; if (elapsed <= 0) return 0.0;
const uploaded = self.total_uploaded.load(.acquire); const uploaded = self.total_uploaded.load(.acquire);
@@ -287,20 +294,20 @@ pub const NetworkSender = *const fn (peer_id: []const u8, data: []const u8, cont
/// MED-8 FIX: Made thread-safe with proper atomic operations /// MED-8 FIX: Made thread-safe with proper atomic operations
pub const BandwidthLimiter = struct { pub const BandwidthLimiter = struct {
/// MED-8 FIX: max_bandwidth is now atomic to prevent torn reads/writes /// MED-8 FIX: max_bandwidth is now atomic to prevent torn reads/writes
max_bandwidth: atomic.Value(u64), max_bandwidth: AtomicValue(u64),
current_bandwidth: atomic.Value(u64), current_bandwidth: AtomicValue(u64),
time_window: i64, // Time window for bandwidth calculation (seconds) time_window: i64, // Time window for bandwidth calculation (seconds)
last_reset: atomic.Value(i64), last_reset: AtomicValue(i64),
/// MED-8 FIX: Mutex to coordinate checkAndReset across threads /// MED-8 FIX: Mutex to coordinate checkAndReset across threads
reset_mutex: std.Thread.Mutex = .{}, reset_mutex: Mutex = .{},
allocator: mem.Allocator, allocator: mem.Allocator,
pub fn init(max_bandwidth: u64, time_window: i64, allocator: mem.Allocator) BandwidthLimiter { pub fn init(max_bandwidth: u64, time_window: i64, allocator: mem.Allocator) BandwidthLimiter {
return BandwidthLimiter{ return BandwidthLimiter{
.max_bandwidth = atomic.Value(u64).init(max_bandwidth), .max_bandwidth = AtomicValue(u64).init(max_bandwidth),
.current_bandwidth = atomic.Value(u64).init(0), .current_bandwidth = AtomicValue(u64).init(0),
.time_window = time_window, .time_window = time_window,
.last_reset = atomic.Value(i64).init(std.time.timestamp()), .last_reset = AtomicValue(i64).init(platform_time.timestamp()),
.reset_mutex = .{}, .reset_mutex = .{},
.allocator = allocator, .allocator = allocator,
}; };
@@ -406,7 +413,7 @@ pub const BandwidthLimiter = struct {
/// Reset bandwidth usage if time window has passed /// Reset bandwidth usage if time window has passed
/// MED-8 FIX: Uses mutex to prevent torn state from concurrent resets /// MED-8 FIX: Uses mutex to prevent torn state from concurrent resets
fn checkAndReset(self: *BandwidthLimiter) void { fn checkAndReset(self: *BandwidthLimiter) void {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const last_reset_time = self.last_reset.load(.acquire); const last_reset_time = self.last_reset.load(.acquire);
if (now - last_reset_time >= self.time_window) { if (now - last_reset_time >= self.time_window) {
@@ -449,7 +456,7 @@ pub const UploadManager = struct {
/// Total file size for boundary checking /// Total file size for boundary checking
file_size: u64, file_size: u64,
/// PERF FIX: Cached file handle to avoid open/close per piece /// PERF FIX: Cached file handle to avoid open/close per piece
cached_file: ?std.fs.File, cached_file: ?filesystem.File,
/// PERF: Memory-mapped file for zero-copy reads (used for large files) /// PERF: Memory-mapped file for zero-copy reads (used for large files)
mapped_file: ?MappedFile, mapped_file: ?MappedFile,
/// Network sender callback for transmitting data /// Network sender callback for transmitting data
@@ -459,7 +466,7 @@ pub const UploadManager = struct {
/// Message serializer for encoding protocol messages /// Message serializer for encoding protocol messages
message_serializer: serializer.MessageSerializer, message_serializer: serializer.MessageSerializer,
/// Mutex protecting all hashmaps and lists /// Mutex protecting all hashmaps and lists
manager_mutex: std.Thread.Mutex = .{}, manager_mutex: Mutex = .{},
pub fn init( pub fn init(
max_bandwidth: u64, max_bandwidth: u64,
@@ -519,8 +526,8 @@ pub const UploadManager = struct {
} }
// Close any existing cached file handle // Close any existing cached file handle
if (self.cached_file) |file| { if (self.cached_file != null) {
file.close(); self.cached_file.?.close();
self.cached_file = null; self.cached_file = null;
} }
@@ -536,7 +543,7 @@ pub const UploadManager = struct {
// PERF FIX: Open and cache the file handle for all future reads // PERF FIX: Open and cache the file handle for all future reads
// This is needed even when mmap is used, for fallback and getReadInfo() compatibility // This is needed even when mmap is used, for fallback and getReadInfo() compatibility
self.cached_file = std.fs.cwd().openFile(file_path, .{}) catch |err| { self.cached_file = FileSystem.openFile(file_path, .{}) catch |err| {
std.log.warn("setFilePath: failed to open file for caching: {}", .{err}); std.log.warn("setFilePath: failed to open file for caching: {}", .{err});
return Error.FileError; return Error.FileError;
}; };
@@ -544,8 +551,8 @@ pub const UploadManager = struct {
// PERF: Try to use mmap for large files (zero-copy reads) // PERF: Try to use mmap for large files (zero-copy reads)
// CASCADE FIX: Skip mmap for files being actively written - MAP_PRIVATE may // CASCADE FIX: Skip mmap for files being actively written - MAP_PRIVATE may
// return stale data when pages are modified via pwrite on another handle. // return stale data when pages are modified via pwrite on another handle.
if (!disable_mmap and file_mod.shouldUseMmap(file_size)) { if (!is_wasm and !disable_mmap and file_mod.shouldUseMmap(file_size)) {
if (MappedFile.initFromHandle(self.cached_file.?, file_size)) |mf| { if (MappedFile.initFromHandle(self.cached_file.?.impl.real, file_size)) |mf| {
self.mapped_file = mf; self.mapped_file = mf;
std.log.info("setFilePath: using mmap for {d} MB file", .{file_size / (1024 * 1024)}); std.log.info("setFilePath: using mmap for {d} MB file", .{file_size / (1024 * 1024)});
} else |_| { } else |_| {
@@ -621,11 +628,11 @@ pub const UploadManager = struct {
// PERF FIX: Use cached file handle instead of opening file per piece // PERF FIX: Use cached file handle instead of opening file per piece
// Note: bandwidth is already consumed even if read fails (safer than over-consumption) // Note: bandwidth is already consumed even if read fails (safer than over-consumption)
const cached = self.cached_file orelse { if (self.cached_file == null) {
std.log.warn("readPieceData: no cached file handle", .{}); std.log.warn("readPieceData: no cached file handle", .{});
return Error.FileError; return Error.FileError;
}; }
const data = self.file_chunker.readPieceFromHandle(cached, piece_index, actual_length) catch |err| { const data = self.file_chunker.readPieceFromHandle(&self.cached_file.?, piece_index, actual_length) catch |err| {
std.log.warn("readPieceData: readPieceFromHandle failed: {}", .{err}); std.log.warn("readPieceData: readPieceFromHandle failed: {}", .{err});
return Error.FileError; return Error.FileError;
}; };
@@ -642,7 +649,7 @@ pub const UploadManager = struct {
/// PERF: Get info needed for mutex-free pread operations /// PERF: Get info needed for mutex-free pread operations
/// Returns file handle and calculated absolute offset for direct pread /// Returns file handle and calculated absolute offset for direct pread
/// Call this while holding sessions_mutex, then release mutex and do pread directly /// Call this while holding sessions_mutex, then release mutex and do pread directly
pub fn getReadInfo(self: *UploadManager, piece_index: u32, offset: u64, length: u32) Error!struct { file: std.fs.File, absolute_offset: u64, actual_length: u32, piece_available: bool } { pub fn getReadInfo(self: *UploadManager, piece_index: u32, offset: u64, length: u32) Error!struct { file: filesystem.File, absolute_offset: u64, actual_length: u32, piece_available: bool } {
// Check piece availability // Check piece availability
self.manager_mutex.lock(); self.manager_mutex.lock();
const piece_available = self.available_pieces.contains(piece_index); const piece_available = self.available_pieces.contains(piece_index);
@@ -693,9 +700,9 @@ pub const UploadManager = struct {
// The file handle was closed by mmap deinit, clear cached_file // The file handle was closed by mmap deinit, clear cached_file
// to prevent double-close // to prevent double-close
self.cached_file = null; self.cached_file = null;
} else if (self.cached_file) |file| { } else if (self.cached_file != null) {
// Only close cached_file if mmap wasn't used // Only close cached_file if mmap wasn't used
file.close(); self.cached_file.?.close();
self.cached_file = null; self.cached_file = null;
} }
// Free the owned file path copy // Free the owned file path copy
@@ -710,7 +717,7 @@ pub const UploadManager = struct {
const piece = AvailablePiece{ const piece = AvailablePiece{
.index = piece_index, .index = piece_index,
.hash = hash, .hash = hash,
.available_at = std.time.timestamp(), .available_at = platform_time.timestamp(),
.upload_count = 0, .upload_count = 0,
.is_verified = true, .is_verified = true,
}; };
@@ -827,7 +834,7 @@ pub const UploadManager = struct {
const active_upload = ActiveUpload{ const active_upload = ActiveUpload{
.request = request, .request = request,
.bytes_sent = 0, .bytes_sent = 0,
.started_at = std.time.timestamp(), .started_at = platform_time.timestamp(),
.status = .uploading, .status = .uploading,
}; };
@@ -1171,8 +1178,8 @@ fn compareUploadRequests(_: void, a: UploadRequest, b: UploadRequest) bool {
} }
// Then by time waited (older first) // Then by time waited (older first)
const time_a = std.time.timestamp() - a.requested_at; const time_a = platform_time.timestamp() - a.requested_at;
const time_b = std.time.timestamp() - b.requested_at; const time_b = platform_time.timestamp() - b.requested_at;
if (time_a != time_b) { if (time_a != time_b) {
return time_a > time_b; return time_a > time_b;
} }
@@ -1301,7 +1308,7 @@ pub const UploadQueue = struct {
// IMP-M5 FIX: Use current time if no uploads exist // IMP-M5 FIX: Use current time if no uploads exist
if (earliest_start == std.math.maxInt(i64)) { if (earliest_start == std.math.maxInt(i64)) {
earliest_start = std.time.timestamp(); earliest_start = platform_time.timestamp();
} }
return CombinedUploadStats{ return CombinedUploadStats{
@@ -1329,7 +1336,7 @@ pub const CombinedUploadStats = struct {
/// Get average upload speed /// Get average upload speed
/// IMP-M5 FIX: Now properly uses elapsed time for speed calculation /// IMP-M5 FIX: Now properly uses elapsed time for speed calculation
pub fn getAverageSpeed(self: CombinedUploadStats) f32 { pub fn getAverageSpeed(self: CombinedUploadStats) f32 {
const now = std.time.timestamp(); const now = platform_time.timestamp();
const elapsed = now - self.start_time; const elapsed = now - self.start_time;
// IMP-M5 FIX: Guard against division by zero and negative elapsed // IMP-M5 FIX: Guard against division by zero and negative elapsed
@@ -1341,7 +1348,7 @@ pub const CombinedUploadStats = struct {
/// Get elapsed time in seconds /// Get elapsed time in seconds
pub fn getElapsedTime(self: CombinedUploadStats) i64 { pub fn getElapsedTime(self: CombinedUploadStats) i64 {
return std.time.timestamp() - self.start_time; return platform_time.timestamp() - self.start_time;
} }
}; };
@@ -1402,7 +1409,7 @@ test "upload request operations" {
try testing.expect(!request.isExpired(60)); // Not expired with 60s timeout try testing.expect(!request.isExpired(60)); // Not expired with 60s timeout
// Force expiration by setting requested_at in the past // Force expiration by setting requested_at in the past
request.requested_at = std.time.timestamp() - 10; request.requested_at = platform_time.timestamp() - 10;
try testing.expect(request.isExpired(5)); // Expired: 10 seconds ago > 5s timeout try testing.expect(request.isExpired(5)); // Expired: 10 seconds ago > 5s timeout
try testing.expect(!request.isExpired(15)); // Not expired: 10 seconds ago <= 15s timeout try testing.expect(!request.isExpired(15)); // Not expired: 10 seconds ago <= 15s timeout
} }

View File

@@ -8,9 +8,15 @@
//! limits multi-peer download throughput. //! limits multi-peer download throughput.
const std = @import("std"); const std = @import("std");
const atomic = std.atomic; const platform_time = @import("platform").time;
const sync = @import("sync");
const Mutex = sync.Mutex;
const AtomicValue = sync.AtomicValue;
const builtin = @import("builtin");
const mem = std.mem; const mem = std.mem;
const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64;
const core = @import("core"); const core = @import("core");
const Error = core.errors.Error; const Error = core.errors.Error;
const hash_mod = @import("hash.zig"); const hash_mod = @import("hash.zig");
@@ -97,29 +103,29 @@ pub const VerificationPool = struct {
/// Task queue for pending verifications /// Task queue for pending verifications
task_queue: std.ArrayList(VerificationTask), task_queue: std.ArrayList(VerificationTask),
task_mutex: std.Thread.Mutex, task_mutex: Mutex,
/// Condition variable for worker wakeup /// Condition variable for worker wakeup (not available on WASM)
task_condition: std.Thread.Condition, task_condition: if (is_wasm) void else std.Thread.Condition,
/// Results queue (if use_results_queue is true) /// Results queue (if use_results_queue is true)
results_queue: std.ArrayList(VerificationResult), results_queue: std.ArrayList(VerificationResult),
results_mutex: std.Thread.Mutex, results_mutex: Mutex,
/// Worker threads /// Worker threads (not available on WASM — use processSynchronously instead)
workers: std.ArrayList(std.Thread), workers: if (is_wasm) void else std.ArrayList(std.Thread),
/// Shutdown flag /// Shutdown flag
shutdown: atomic.Value(bool), shutdown: AtomicValue(bool),
/// PERF: Pre-allocated buffer pool for piece data /// PERF: Pre-allocated buffer pool for piece data
buffer_pool: ?*PieceBufferPool, buffer_pool: ?*PieceBufferPool,
/// Statistics /// Statistics
tasks_completed: atomic.Value(u64), tasks_completed: AtomicValue(u64),
tasks_failed: atomic.Value(u64), tasks_failed: AtomicValue(u64),
total_bytes_verified: atomic.Value(u64), total_bytes_verified: AtomicValue(u64),
pool_hits: atomic.Value(u64), pool_hits: AtomicValue(u64),
pool_misses: atomic.Value(u64), pool_misses: AtomicValue(u64),
pub fn init(allocator: mem.Allocator, config: VerificationPoolConfig) Error!VerificationPool { pub fn init(allocator: mem.Allocator, config: VerificationPoolConfig) Error!VerificationPool {
// Initialize buffer pool if configured // Initialize buffer pool if configured
@@ -146,17 +152,17 @@ pub const VerificationPool = struct {
.config = config, .config = config,
.task_queue = .{}, .task_queue = .{},
.task_mutex = .{}, .task_mutex = .{},
.task_condition = .{}, .task_condition = if (is_wasm) {} else .{},
.results_queue = .{}, .results_queue = .{},
.results_mutex = .{}, .results_mutex = .{},
.workers = .{}, .workers = if (is_wasm) {} else .{},
.shutdown = atomic.Value(bool).init(false), .shutdown = AtomicValue(bool).init(false),
.buffer_pool = buffer_pool, .buffer_pool = buffer_pool,
.tasks_completed = atomic.Value(u64).init(0), .tasks_completed = AtomicValue(u64).init(0),
.tasks_failed = atomic.Value(u64).init(0), .tasks_failed = AtomicValue(u64).init(0),
.total_bytes_verified = atomic.Value(u64).init(0), .total_bytes_verified = AtomicValue(u64).init(0),
.pool_hits = atomic.Value(u64).init(0), .pool_hits = AtomicValue(u64).init(0),
.pool_misses = atomic.Value(u64).init(0), .pool_misses = AtomicValue(u64).init(0),
}; };
} }
@@ -170,7 +176,7 @@ pub const VerificationPool = struct {
self.task_queue.deinit(self.allocator); self.task_queue.deinit(self.allocator);
self.results_queue.deinit(self.allocator); self.results_queue.deinit(self.allocator);
self.workers.deinit(self.allocator); if (!is_wasm) self.workers.deinit(self.allocator);
// Clean up buffer pool // Clean up buffer pool
if (self.buffer_pool) |pool| { if (self.buffer_pool) |pool| {
@@ -179,8 +185,10 @@ pub const VerificationPool = struct {
} }
} }
/// Start worker threads /// Start worker threads (no-op on WASM — use processSynchronously instead)
pub fn start(self: *VerificationPool) Error!void { pub fn start(self: *VerificationPool) Error!void {
if (is_wasm) return;
const num_workers = if (self.config.num_workers == 0) const num_workers = if (self.config.num_workers == 0)
@as(u32, @intCast(@max(1, std.Thread.getCpuCount() catch 4))) @as(u32, @intCast(@max(1, std.Thread.getCpuCount() catch 4)))
else else
@@ -197,8 +205,10 @@ pub const VerificationPool = struct {
} }
} }
/// Stop all worker threads /// Stop all worker threads (no-op on WASM)
pub fn stop(self: *VerificationPool) void { pub fn stop(self: *VerificationPool) void {
if (is_wasm) return;
self.shutdown.store(true, .release); self.shutdown.store(true, .release);
// Wake up all workers // Wake up all workers
@@ -213,6 +223,49 @@ pub const VerificationPool = struct {
self.workers.clearRetainingCapacity(); self.workers.clearRetainingCapacity();
} }
/// Process up to `max_tasks` pending verifications synchronously.
/// For WASM: call this from the update loop since threads are unavailable.
/// On native: this can also be used for single-threaded operation.
pub fn processSynchronously(self: *VerificationPool, max_tasks: u32) void {
var processed: u32 = 0;
while (processed < max_tasks) : (processed += 1) {
// Dequeue a task
var task: VerificationTask = undefined;
{
self.task_mutex.lock();
defer self.task_mutex.unlock();
if (self.task_queue.items.len == 0) break;
task = self.task_queue.orderedRemove(0);
}
// Process it
const task_data = task.getData();
const is_valid = HashUtils.verify(task_data, task.expected_hash) catch false;
const data_len = task_data.len;
const peer_id = task.peer_id;
task.deinit();
_ = self.tasks_completed.fetchAdd(1, .release);
_ = self.total_bytes_verified.fetchAdd(data_len, .release);
if (!is_valid) {
_ = self.tasks_failed.fetchAdd(1, .release);
}
if (self.config.use_results_queue) {
self.results_mutex.lock();
defer self.results_mutex.unlock();
self.results_queue.append(self.allocator, .{
.session_id = task.session_id,
.piece_index = task.piece_index,
.is_valid = is_valid,
.completed_at = platform_time.milliTimestamp(),
.peer_id = peer_id,
}) catch {};
}
}
}
/// Queue a piece for verification /// Queue a piece for verification
/// The data is COPIED - caller can free their copy after this returns /// The data is COPIED - caller can free their copy after this returns
/// Returns error if queue is full or allocation fails /// Returns error if queue is full or allocation fails
@@ -268,7 +321,7 @@ pub const VerificationPool = struct {
.peer_id = peer_id, .peer_id = peer_id,
}) catch return Error.OutOfMemory; }) catch return Error.OutOfMemory;
self.task_condition.signal(); if (!is_wasm) self.task_condition.signal();
} }
/// Get next completed result (non-blocking) /// Get next completed result (non-blocking)
@@ -354,7 +407,7 @@ pub const VerificationPool = struct {
.session_id = t.session_id, .session_id = t.session_id,
.piece_index = t.piece_index, .piece_index = t.piece_index,
.is_valid = is_valid, .is_valid = is_valid,
.completed_at = std.time.milliTimestamp(), .completed_at = platform_time.milliTimestamp(),
.peer_id = peer_id, .peer_id = peer_id,
}) catch |err| { }) catch |err| {
std.log.err("Failed to queue verification result for piece {}: {} - result lost", .{ t.piece_index, err }); std.log.err("Failed to queue verification result for piece {}: {} - result lost", .{ t.piece_index, err });

View File

@@ -449,7 +449,7 @@ test "UploadManager.init creates manager with correct state" {
try testing.expectEqual(@as(?[]const u8, null), manager.file_path); try testing.expectEqual(@as(?[]const u8, null), manager.file_path);
try testing.expectEqual(@as(u64, 0), manager.file_size); try testing.expectEqual(@as(u64, 0), manager.file_size);
try testing.expectEqual(@as(?std.fs.File, null), manager.cached_file); try testing.expectEqual(@as(?files.filesystem.File, null), manager.cached_file);
} }
test "UploadManager.addAvailablePiece and removeAvailablePiece" { test "UploadManager.addAvailablePiece and removeAvailablePiece" {