From 4c1927588d801b34b60e1d0c43dd26241f7d66be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Muhammed=20Tanr=C4=B1kulu?= Date: Thu, 19 Feb 2026 11:34:07 -0300 Subject: [PATCH] feat: refactor files module: platform abstractions, filesystem error handling --- src/files/adaptive_concurrency.zig | 3 +- src/files/download.zig | 73 ++-- src/files/file.zig | 104 +++--- src/files/filesystem.zig | 554 +++++++++++++++++++++++------ src/files/hash.zig | 9 +- src/files/manager.zig | 142 ++++---- src/files/mock_fs.zig | 13 +- src/files/path_security.zig | 27 ++ src/files/peer_metrics.zig | 10 +- src/files/piece.zig | 3 +- src/files/piece_buffer_pool.zig | 26 +- src/files/piece_pipeline.zig | 101 ++++-- src/files/transfer.zig | 197 +++++----- src/files/upload.zig | 103 +++--- src/files/verification_pool.zig | 105 ++++-- tests/files/test_upload.zig | 2 +- 16 files changed, 998 insertions(+), 474 deletions(-) diff --git a/src/files/adaptive_concurrency.zig b/src/files/adaptive_concurrency.zig index a9583ca..3e6aaf3 100644 --- a/src/files/adaptive_concurrency.zig +++ b/src/files/adaptive_concurrency.zig @@ -10,6 +10,7 @@ //! based on success/timeout rates, similar to TCP congestion control. const std = @import("std"); +const platform_time = @import("platform").time; pub const AdaptiveConcurrencyController = struct { // Configuration (set at init, immutable) @@ -86,7 +87,7 @@ pub const AdaptiveConcurrencyController = struct { self: *AdaptiveConcurrencyController, current_in_flight: usize, ) void { - const now = std.time.nanoTimestamp(); + const now = platform_time.nanoTimestamp(); const total = self.cycle_successes + self.cycle_timeouts; if (total > 0) { diff --git a/src/files/download.zig b/src/files/download.zig index d6c25e8..8489a65 100644 --- a/src/files/download.zig +++ b/src/files/download.zig @@ -4,9 +4,15 @@ //! peer coordination, and download progress tracking. 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 mem = std.mem; -const atomic = std.atomic; const fmt = std.fmt; const core = @import("core"); @@ -14,6 +20,7 @@ const Error = core.errors.Error; const hash = @import("hash.zig"); const PieceHash = hash.PieceHash; const HashUtils = hash.HashUtils; +const filesystem = @import("filesystem.zig"); const file = @import("file.zig"); const FileChunker = file.FileChunker; const FileWriter = file.FileWriter; @@ -75,7 +82,7 @@ pub const DownloadRequest = struct { .offset = offset, .length = length, .priority = priority, - .requested_at = std.time.timestamp(), + .requested_at = platform_time.timestamp(), .peer_id = owned_peer_id, }; } @@ -87,7 +94,7 @@ pub const DownloadRequest = struct { /// Check if request has expired 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. pub const DownloadState = struct { total_size: u64, - downloaded_bytes: atomic.Value(u64), - verified_bytes: atomic.Value(u64), + downloaded_bytes: AtomicValue(u64), + verified_bytes: AtomicValue(u64), piece_count: u32, - completed_pieces: atomic.Value(u32), - failed_pieces: atomic.Value(u32), + completed_pieces: AtomicValue(u32), + failed_pieces: AtomicValue(u32), start_time: i64, pub fn init(total_size: u64, piece_count: u32) DownloadState { return DownloadState{ .total_size = total_size, - .downloaded_bytes = atomic.Value(u64).init(0), - .verified_bytes = atomic.Value(u64).init(0), + .downloaded_bytes = AtomicValue(u64).init(0), + .verified_bytes = AtomicValue(u64).init(0), .piece_count = piece_count, - .completed_pieces = atomic.Value(u32).init(0), - .failed_pieces = atomic.Value(u32).init(0), - .start_time = std.time.timestamp(), + .completed_pieces = AtomicValue(u32).init(0), + .failed_pieces = AtomicValue(u32).init(0), + .start_time = platform_time.timestamp(), }; } @@ -170,7 +177,7 @@ pub const DownloadState = struct { /// Get download speed (bytes per second) /// HIGH-4 FIX: Uses acquire ordering to see latest writes. pub fn getDownloadSpeed(self: *DownloadState) f32 { - const elapsed = std.time.timestamp() - self.start_time; + const elapsed = platform_time.timestamp() - self.start_time; if (elapsed <= 0) return 0.0; const downloaded = self.downloaded_bytes.load(.acquire); @@ -515,11 +522,11 @@ pub const DownloadManager = struct { file_path: ?[]const u8, request_timeout: i64, /// Mutex protecting all hashmaps and lists - manager_mutex: std.Thread.Mutex = .{}, + manager_mutex: Mutex = .{}, /// ADAPTIVE: Count of stuck downloads cleaned up since last query /// Used by adaptive concurrency controller to detect network issues - stuck_downloads_cleaned: atomic.Value(u32) = atomic.Value(u32).init(0), + stuck_downloads_cleaned: AtomicValue(u32) = AtomicValue(u32).init(0), // PERF: Endgame mode - request remaining pieces from ALL peers /// Whether endgame mode is active (last few pieces) @@ -542,7 +549,7 @@ pub const DownloadManager = struct { piece_size: u64, allocator: mem.Allocator, ) Error!DownloadManager { - const seed = std.crypto.random.int(u64); + const seed = platform_random.int(u64); const selector = PieceSelector.init(strategy, seed, allocator); return DownloadManager{ @@ -819,7 +826,7 @@ pub const DownloadManager = struct { .offset = 0, .length = @intCast(self.piece_size), .priority = .high, // Boost priority for retried pieces - .requested_at = std.time.timestamp(), + .requested_at = platform_time.timestamp(), }) catch { 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, .length = request.length, .downloaded_bytes = 0, - .started_at = std.time.timestamp(), + .started_at = platform_time.timestamp(), .status = .downloading, }; @@ -1564,7 +1571,7 @@ pub const DownloadManager = struct { /// This function detects and removes such stuck downloads so they can be retried. /// CONCURRENCY FIX: Batch size now matches max_concurrent to handle all stuck downloads in one pass. fn cleanupStuckActiveDownloadsLocked(self: *DownloadManager, max_concurrent: usize) void { - const now = std.time.timestamp(); + const now = platform_time.timestamp(); // THROUGHPUT FIX: 10 seconds provides a balance between fast retry and avoiding // premature retries. 5 seconds was too aggressive and caused excessive retries. // 15 seconds was too slow for localhost. For WAN, consider 15 seconds. @@ -1654,7 +1661,7 @@ pub const DownloadManager = struct { .offset = piece_offset, .length = piece_size_u32, .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. // Using the same failed peer_id would cause the retry to fail again. // This matches the behavior in cancelActiveDownloadsFromPeerLocked. @@ -1982,7 +1989,7 @@ pub const DownloadManager = struct { /// PERF: Get info needed for mutex-free pwrite operations /// Returns file handle and calculated absolute offset for direct pwrite /// Call this while holding mutex, then release mutex and do pwrite directly - pub fn getWriteInfo(self: *DownloadManager, piece_index: u32, offset: u64) Error!struct { file: std.fs.File, absolute_offset: u64, file_path: []const u8 } { + 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 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 pub fn verifyPiece(self: *DownloadManager, piece_index: u32, expected_hash: *const PieceHash) Error!bool { + if (is_wasm) return Error.OperationNotSupported; + // Get file path 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); // 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(); // Seek to piece position @@ -2100,6 +2109,8 @@ pub const DownloadManager = struct { /// Save current download state to a resume file /// The resume file stores which pieces are completed, allowing downloads to continue after restart pub fn saveResumeState(self: *DownloadManager, resume_path: []const u8) Error!void { + if (is_wasm) return Error.OperationNotSupported; + self.manager_mutex.lock(); defer self.manager_mutex.unlock(); @@ -2109,7 +2120,7 @@ pub const DownloadManager = struct { } // 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(); // Build header @@ -2163,13 +2174,15 @@ pub const DownloadManager = struct { expected_content_hash: ?[32]u8, strategy: SelectionStrategy, ) Error!?DownloadManager { + if (is_wasm) return null; + // Validate path if (!path_security.PathValidator.isPathSafe(resume_path)) { return Error.InvalidData; } // Open resume file - var resume_file = std.fs.cwd().openFile(resume_path, .{}) catch return null; + var resume_file = filesystem.FileSystem.openFile(resume_path, .{}) catch return null; defer resume_file.close(); // Read header @@ -2278,13 +2291,15 @@ pub const DownloadManager = struct { self: *DownloadManager, piece_hashes: []const PieceHash, ) Error!u32 { + if (is_wasm) return Error.OperationNotSupported; + self.manager_mutex.lock(); defer self.manager_mutex.unlock(); const file_path = self.file_path orelse return Error.FileError; // Open file for reading - var data_file = std.fs.cwd().openFile(file_path, .{}) catch return Error.FileError; + var data_file = filesystem.FileSystem.openFile(file_path, .{}) catch return Error.FileError; defer data_file.close(); var failed_count: u32 = 0; @@ -2369,7 +2384,9 @@ pub const DownloadManager = struct { /// Delete the resume state file (call after successful download completion) pub fn deleteResumeState(resume_path: []const u8) void { - std.fs.cwd().deleteFile(resume_path) catch |err| { + if (is_wasm) return; + + filesystem.FileSystem.deleteFile(resume_path) catch |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 pub fn recordFailure(self: *PieceRetryTracker, peer: []const u8) void { 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 if (peer.len >= 32) { var peer_copy: [32]u8 = undefined; @@ -2451,7 +2468,7 @@ pub const PieceRetryTracker = struct { if (!self.shouldRetry()) return false; if (self.retry_count == 0) return true; - const now = std.time.milliTimestamp(); + const now = platform_time.milliTimestamp(); const delay = self.getRetryDelay(); return (now - self.last_attempt) >= delay; } diff --git a/src/files/file.zig b/src/files/file.zig index 52ffa64..8f67c16 100644 --- a/src/files/file.zig +++ b/src/files/file.zig @@ -9,6 +9,7 @@ const mem = std.mem; const fs = std.fs; const fmt = std.fmt; const builtin = @import("builtin"); +const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64; const core = @import("core"); const Error = core.errors.Error; @@ -185,7 +186,7 @@ pub const FileChunker = struct { const current_piece_size = @min(self.piece_size, remaining); // 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); const bytes_read = file.read(piece_data) catch return Error.FileError; @@ -227,28 +228,28 @@ pub const FileChunker = struct { return Error.InvalidData; } - // Open the file - const file = fs.cwd().openFile(file_path, .{}) catch |err| { + // Open the file via FileSystem abstraction + var file = FileSystem.openFile(file_path, .{}) catch |err| { std.log.warn("readPiece: openFile failed for '{s}': {}", .{ file_path, err }); return Error.FileError; }; 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. /// 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); } - 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 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 // 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| { std.log.warn("readPiece: preadAll failed: {}", .{err}); self.allocator.free(piece_data); @@ -274,14 +275,14 @@ pub const FileChunker = struct { piece_index: u32, piece_data: []const u8, ) Error!void { - const file = fs.cwd().openFile(file_path, .{ + var file = FileSystem.openFile(file_path, .{ .mode = .write_only, }) catch return Error.FileError; defer file.close(); // OVERFLOW FIX: Use checked multiplication to prevent overflow const offset = std.math.mul(u64, piece_index, self.piece_size) catch return Error.BufferOverflow; - + // Seek to piece position file.seekTo(offset) catch return Error.FileError; @@ -776,6 +777,9 @@ pub const FileUtils = struct { /// Check if sufficient disk space is available 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 "."; if (builtin.os.tag == .linux or builtin.os.tag == .macos) { @@ -995,17 +999,17 @@ pub fn checkDiskSpace(path: []const u8, required_bytes: u64) Error!void { pub const FileReader = struct { allocator: mem.Allocator, file_path: []const u8, - file: fs.File, + file: FSFile, buffer_size: usize, - + pub fn init(file_path: []const u8, allocator: mem.Allocator, buffer_size: usize) Error!FileReader { // Validate path before opening if (!path_security.PathValidator.isPathSafe(file_path)) { 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{ .allocator = allocator, .file_path = file_path, @@ -1058,8 +1062,8 @@ pub const FileReader = struct { pub const FileWriter = struct { allocator: mem.Allocator, file_path: []const u8, - file: fs.File, - + file: FSFile, + pub fn init(file_path: []const u8, allocator: mem.Allocator, file_size: ?u64) Error!FileWriter { 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 - const file = fs.cwd().createFile(file_path, .{ + var file = FileSystem.createFile(file_path, .{ .truncate = truncate, .read = true, }) catch return Error.FileError; // PERF: Pre-allocate file if size is known (reduces fragmentation, faster writes) if (file_size) |size| { - preallocateFile(file, size); + preallocateFile(&file, size); } return FileWriter{ @@ -1108,21 +1112,27 @@ pub const FileWriter = struct { } /// 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 if (builtin.os.tag == .linux) { - // FALLOC_FL_KEEP_SIZE = 0x01 - allocate without changing file size - const FALLOC_FL_KEEP_SIZE = 0x01; - const fd = file.handle; - const result = std.os.linux.syscall4(.fallocate, - @as(usize, @intCast(fd)), - @as(usize, FALLOC_FL_KEEP_SIZE), - @as(usize, 0), // offset - @as(usize, @intCast(size)), - ); - if (result == 0) { - std.log.debug("PERF: Pre-allocated {} MB with fallocate", .{size / (1024 * 1024)}); - return; + if (!is_wasm) { + // FALLOC_FL_KEEP_SIZE = 0x01 - allocate without changing file size + const FALLOC_FL_KEEP_SIZE = 0x01; + const real_file = file.impl.real; + const fd = real_file.handle; + const result = std.os.linux.syscall4(.fallocate, + @as(usize, @intCast(fd)), + @as(usize, FALLOC_FL_KEEP_SIZE), + @as(usize, 0), // offset + @as(usize, @intCast(size)), + ); + if (result == 0) { + std.log.debug("PERF: Pre-allocated {} MB with fallocate", .{size / (1024 * 1024)}); + return; + } } // 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 - 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; } @@ -1186,8 +1198,9 @@ pub const FileWriter = struct { // 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. - if (builtin.os.tag == .macos) { - const handle = self.file.handle; + if (!is_wasm and builtin.os.tag == .macos) { + const real_file = self.file.impl.real; + const handle = real_file.handle; const F_FULLFSYNC = 51; // From _ = std.c.fcntl(handle, F_FULLFSYNC, @as(c_int, 0)); // Ignore error - not all drives support F_FULLFSYNC @@ -1198,7 +1211,7 @@ pub const FileWriter = struct { pub fn close(self: *FileWriter) void { self.file.close(); } - + pub fn deinit(self: *FileWriter) void { // CRITICAL FIX: Sync data to disk before closing to ensure all writes are persisted. // Without this, data may remain in OS buffer cache and verification after stop() fails. @@ -1237,11 +1250,11 @@ pub const MMAP_MAX_SIZE: u64 = 2 * 1024 * 1024 * 1024; /// ``` pub const MappedFile = struct { /// 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 file_size: u64, - /// File handle (kept open while mapped) - file: fs.File, + /// File handle (kept open while mapped) — void on WASM (mmap not supported) + file: if (is_wasm) void else fs.File, /// Initialize memory-mapped file for reading /// 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 pub fn initWithLimits(file_path: []const u8, min_size: u64, max_size: u64) Error!MappedFile { + if (is_wasm) return Error.OperationNotSupported; + // Validate path if (!PathValidator.isPathSafe(file_path)) { return Error.InvalidData; @@ -1289,7 +1304,9 @@ pub const MappedFile = struct { } /// 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) { return Error.InvalidData; } @@ -1347,27 +1364,28 @@ pub const MappedFile = struct { /// Advise the kernel about access patterns (optimization hint) 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); } } /// Advise random access pattern 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); } } /// Pre-fault pages into memory (reduce page faults during reads) 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); } } /// Release resources pub fn deinit(self: *MappedFile) void { + if (is_wasm) return; // Unmap memory std.posix.munmap(self.data); // Close file @@ -1375,7 +1393,9 @@ pub const MappedFile = struct { } /// 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); // Use mmap on POSIX systems diff --git a/src/files/filesystem.zig b/src/files/filesystem.zig index 8418615..f277b44 100644 --- a/src/files/filesystem.zig +++ b/src/files/filesystem.zig @@ -1,13 +1,14 @@ //! Filesystem Abstraction Layer //! //! Provides a unified interface for filesystem operations that can be backed by -//! either the real filesystem (std.fs) or an in-memory mock filesystem for testing. +//! either the real filesystem (std.fs), an in-memory mock filesystem for testing, +//! or a WASM/JS-backed filesystem for browser environments. //! //! Usage: //! ```zig //! 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", .{}); //! defer file.close(); //! @@ -18,10 +19,13 @@ //! To use MockFS in tests, set `use_mock_fs = true` before importing. const std = @import("std"); +const platform_time = @import("platform").time; const builtin = @import("builtin"); const Allocator = std.mem.Allocator; 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 /// Set this in test files before importing filesystem.zig 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 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 pub const Stat = struct { size: u64, ctime: i128, mtime: 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 { impl: FileImpl, - const FileImpl = union(enum) { - real: std.fs.File, - mock: MockFileState, - }; + /// On WASM: mock + wasm variants only (no real filesystem). + /// On native: real + mock variants only (no wasm extern calls). + const FileImpl = if (is_wasm) + union(enum) { mock: MockFileState, wasm: WasmFileState } + else + union(enum) { real: std.fs.File, mock: MockFileState }; const MockFileState = struct { fs: *mock_fs.MockFS, @@ -54,150 +93,279 @@ pub const File = struct { read_only: bool, }; + // ---- Mock helpers (shared by both WASM and native) ---- + + fn mockRead(state: *MockFileState, buffer: []u8) !usize { + const file = state.fs.files.get(state.path) orelse return error.FileNotFound; + const content = file.data; + if (state.position >= content.len) return 0; + const available = content.len - @as(usize, @intCast(state.position)); + const to_read = @min(buffer.len, available); + @memcpy(buffer[0..to_read], content[@intCast(state.position)..][0..to_read]); + state.position += to_read; + return to_read; + } + + fn mockPreadAll(state: MockFileState, buffer: []u8, offset: u64) !usize { + const file = state.fs.files.get(state.path) orelse return error.FileNotFound; + const content = file.data; + const off: usize = @intCast(@min(offset, content.len)); + if (off >= content.len) return 0; + const available = content.len - off; + const to_read = @min(buffer.len, available); + @memcpy(buffer[0..to_read], content[off..][0..to_read]); + return to_read; + } + + fn mockWrite(state: *MockFileState, data: []const u8) !usize { + if (state.read_only) return error.AccessDenied; + const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound; + const end_pos = state.position + data.len; + if (end_pos > file.data.len) { + file.resize(@intCast(end_pos)) catch return error.OutOfMemory; + } + const pos: usize = @intCast(state.position); + @memcpy(file.data[pos..][0..data.len], data); + state.position += data.len; + file.modified_at = platform_time.timestamp(); + return data.len; + } + + fn mockPwriteAll(state: MockFileState, data: []const u8, offset: u64) !void { + if (state.read_only) return error.AccessDenied; + const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound; + const off: usize = @intCast(offset); + if (off + data.len > file.data.len) { + file.resize(off + data.len) catch return error.OutOfMemory; + } + @memcpy(file.data[off..][0..data.len], data); + file.modified_at = platform_time.timestamp(); + } + + fn mockStat(state: MockFileState) !Stat { + const file = state.fs.files.get(state.path) orelse return error.FileNotFound; + return Stat{ + .size = file.data.len, + .ctime = file.created_at, + .mtime = file.modified_at, + .atime = file.modified_at, + }; + } + + 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 { - switch (self.impl) { - .real => |f| return f.read(buffer), - .mock => |*state| { - const file = state.fs.files.get(state.path) orelse return error.FileNotFound; - const content = file.data; - - if (state.position >= content.len) { - return 0; // EOF - } - - const available = content.len - @as(usize, @intCast(state.position)); - const to_read = @min(buffer.len, available); - @memcpy(buffer[0..to_read], content[@intCast(state.position)..][0..to_read]); - state.position += to_read; - return to_read; - }, + 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), + }; } } + /// 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 { - switch (self.impl) { - .real => |f| return f.preadAll(buffer, offset), - .mock => |state| { - const file = state.fs.files.get(state.path) orelse return error.FileNotFound; - const content = file.data; - - const off: usize = @intCast(@min(offset, content.len)); - if (off >= content.len) { - return 0; - } - - const available = content.len - off; - const to_read = @min(buffer.len, available); - @memcpy(buffer[0..to_read], content[off..][0..to_read]); - return to_read; - }, + 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 { - switch (self.impl) { - .real => |f| return f.write(data), - .mock => |*state| { - if (state.read_only) return error.AccessDenied; + 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), + }; + } + } - const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound; - - // Extend file if necessary - const end_pos = state.position + data.len; - if (end_pos > file.data.len) { - file.resize(end_pos) catch return error.OutOfMemory; - } - - // Copy data - const pos: usize = @intCast(state.position); - @memcpy(file.data[pos..][0..data.len], data); - state.position += data.len; - file.modified_at = std.time.timestamp(); - return data.len; - }, + /// Write 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 { - switch (self.impl) { - .real => |f| try f.pwriteAll(data, offset), - .mock => |state| { - if (state.read_only) return error.AccessDenied; - - const file = state.fs.files.getPtr(state.path) orelse return error.FileNotFound; - const off: usize = @intCast(offset); - - // Extend file if necessary - if (off + data.len > file.data.len) { - file.resize(off + data.len) catch return error.OutOfMemory; - } - - // Copy data - @memcpy(file.data[off..][0..data.len], data); - file.modified_at = std.time.timestamp(); - }, + 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 { - switch (self.impl) { - .real => |f| try f.seekTo(position), - .mock => |*state| { - state.position = position; - }, + 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 { - switch (self.impl) { - .real => |f| return f.getPos(), - .mock => |state| return state.position, + 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 { - switch (self.impl) { - .real => |f| { - const s = try f.stat(); - return Stat{ - .size = s.size, - .ctime = s.ctime, - .mtime = s.mtime, - .atime = s.atime, - }; - }, - .mock => |state| { - const file = state.fs.files.get(state.path) orelse return error.FileNotFound; - return Stat{ - .size = file.data.len, - .ctime = file.created_at, - .mtime = file.modified_at, - .atime = file.modified_at, - }; - }, + 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) + /// Sync file to disk (no-op for mock and wasm) pub fn sync(self: *File) !void { - switch (self.impl) { - .real => |f| try f.sync(), - .mock => {}, + if (is_wasm) { + switch (self.impl) { + .mock, .wasm => {}, + } + } else { + switch (self.impl) { + .real => |f| try f.sync(), + .mock => {}, + } } } /// Close file handle pub fn close(self: *File) void { - switch (self.impl) { - .real => |f| f.close(), - .mock => {}, // MockFS doesn't track open handles + if (is_wasm) { + switch (self.impl) { + .mock => {}, + .wasm => |state| wasm_externs.js_file_close(state.file_id), + } + } else { + switch (self.impl) { + .real => |f| f.close(), + .mock => {}, + } } } }; @@ -206,6 +374,26 @@ pub const File = struct { pub const FileSystem = struct { /// Open an existing 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| { // Check if file exists in mock if (!mfs.fileExists(path)) { @@ -230,6 +418,28 @@ pub const FileSystem = struct { /// Create a new file or truncate existing 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| { // Create file in mock (or truncate if exists) mfs.writeFile(path, "") catch |err| switch (err) { @@ -255,6 +465,11 @@ pub const FileSystem = struct { /// Check if file exists 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| { return mfs.fileExists(path); } else { @@ -265,6 +480,20 @@ pub const FileSystem = struct { /// Delete a file 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| { mfs.deleteFile(path) catch |err| switch (err) { error.FileNotFound => return error.FileNotFound, @@ -277,6 +506,20 @@ pub const FileSystem = struct { /// Create directory (and parents) 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| { mfs.makeDir(path) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, @@ -289,6 +532,21 @@ pub const FileSystem = struct { /// Rename/move a file 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| { mfs.rename(old_path, new_path) catch |err| switch (err) { error.FileNotFound => return error.FileNotFound, @@ -299,6 +557,39 @@ pub const FileSystem = struct { 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 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); +} diff --git a/src/files/hash.zig b/src/files/hash.zig index c0bf27b..00a41a8 100644 --- a/src/files/hash.zig +++ b/src/files/hash.zig @@ -7,6 +7,7 @@ //! acceleration (SHA-NI on x86_64, SHA2 extensions on ARM64) when available. const std = @import("std"); +const platform_time = @import("platform").time; const testing = std.testing; const crypto = std.crypto; const mem = std.mem; @@ -157,8 +158,8 @@ pub const FileMetadata = struct { .size = size, .piece_count = @as(u32, @intCast(piece_hashes.len)), .piece_hashes = piece_hashes, - .created_at = std.time.timestamp(), - .modified_at = std.time.timestamp(), + .created_at = platform_time.timestamp(), + .modified_at = platform_time.timestamp(), }; } @@ -274,7 +275,7 @@ pub const HashPool = struct { ) Error!VerificationBatch { var results: std.ArrayList(VerificationResult) = .{}; errdefer results.deinit(self.allocator); - const start_time = std.time.milliTimestamp(); + const start_time = platform_time.milliTimestamp(); var valid_count: u32 = 0; 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)); return VerificationBatch{ diff --git a/src/files/manager.zig b/src/files/manager.zig index c6c0d25..9d629ab 100644 --- a/src/files/manager.zig +++ b/src/files/manager.zig @@ -18,11 +18,16 @@ //! IMPORTANT: Never acquire lower-level locks (0-4) while holding Level 5 locks. 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 is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64; const testing = std.testing; const mem = std.mem; const fmt = std.fmt; -const atomic = std.atomic; const core = @import("core"); const Error = core.errors.Error; @@ -31,6 +36,7 @@ const HashUtils = hash_mod.HashUtils; const FileMetadata = hash_mod.FileMetadata; const PieceHash = hash_mod.PieceHash; const ContentHash = hash_mod.ContentHash; +const filesystem = @import("filesystem.zig"); const file_mod = @import("file.zig"); const FileChunker = file_mod.FileChunker; const FileWriter = file_mod.FileWriter; @@ -161,7 +167,7 @@ pub const PeerReputation = struct { } // 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-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 pub fn recordBadPiece(self: *PeerReputation) void { 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 if (self.bad_pieces >= MAX_BAD_PIECES) { @@ -234,7 +240,7 @@ pub const PeerReputation = struct { const base = getBaseBlacklistDuration(); 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); - 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)", .{ duration, self.blacklist_count, @@ -250,7 +256,7 @@ pub const PeerReputation = struct { /// Check if peer is currently blacklisted 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) @@ -304,7 +310,7 @@ pub const PeerResponseTracker = struct { pub fn init() PeerSlotInfo { return .{ .queued_count = 0, - .last_activity = std.time.timestamp(), + .last_activity = platform_time.timestamp(), .queued_bytes = 0, }; } @@ -417,7 +423,7 @@ pub const PeerResponseTracker = struct { } gop.value_ptr.queued_count += 1; 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; }, .rejected_peer_limit, .rejected_total_limit => return false, @@ -435,7 +441,7 @@ pub const PeerResponseTracker = struct { } else { 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 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) 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); defer to_remove.deinit(); @@ -676,7 +682,7 @@ pub const PreSerializedPieceResponse = struct { off += 1; // 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); off += 4; @@ -685,7 +691,7 @@ pub const PreSerializedPieceResponse = struct { off += 2; // 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); off += 8; @@ -868,7 +874,7 @@ pub const FileSharingSession = struct { const content_hash = try HashUtils.metadataHash(file_metadata); return FileSharingSession{ - .session_id = std.crypto.random.int(u64), + .session_id = platform_random.int(u64), .file_metadata = file_metadata, .content_hash = content_hash, .download_manager = null, @@ -876,8 +882,8 @@ pub const FileSharingSession = struct { .transfer_protocol = TransferProtocol.init(allocator), .piece_pool = PiecePool.init(allocator), .status = .initializing, - .created_at = std.time.timestamp(), - .updated_at = std.time.timestamp(), + .created_at = platform_time.timestamp(), + .updated_at = platform_time.timestamp(), .allocator = allocator, .response_tracker = null, // Initialized when upload starts .pending_piece_responses = .{}, @@ -1016,7 +1022,7 @@ pub const FileSharingSession = struct { /// Update session timestamp pub fn update(self: *FileSharingSession) void { - self.updated_at = std.time.timestamp(); + self.updated_at = platform_time.timestamp(); } /// Check if session is active @@ -1136,19 +1142,19 @@ pub const FileSharingManager = struct { // DownloadManager.manager_mutex is only acquired while holding sessions_mutex, // so it's implicitly ordered after sessions_mutex. // ======================================================================== - sessions_mutex: std.Thread.Mutex = .{}, - file_registry_mutex: std.Thread.Mutex = .{}, - stats_mutex: std.Thread.Mutex = .{}, // Protects messages_sent/failed + sessions_mutex: Mutex = .{}, + file_registry_mutex: Mutex = .{}, + stats_mutex: Mutex = .{}, // Protects messages_sent/failed /// 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. /// Mutations to PeerReputation entries (recordBadPiece, recordGoodPiece) must be done /// while holding this mutex. Read operations via .get() return a copy which is safe /// to use outside the mutex. - reputation_mutex: std.Thread.Mutex = .{}, + reputation_mutex: Mutex = .{}, /// THR-H2 FIX: Protects runtime config modifications (bandwidth limits, strategies, features) /// Config is read during session operations and modified via updateBandwidthLimits, /// setSelectionStrategy, setFeatures. Mutex ensures atomic reads/writes. - config_mutex: std.Thread.Mutex = .{}, + config_mutex: Mutex = .{}, // 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 {}, @@ -1161,7 +1167,7 @@ pub const FileSharingManager = struct { threadlocal var tls_config_held: bool = false; // 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 { // sessions_mutex can only be acquired if we either: @@ -1238,7 +1244,7 @@ pub const FileSharingManager = struct { .use_results_queue = true, // PERF: Pre-allocate buffers for piece verification .num_piece_buffers = config.buffer_pool_size, - .piece_buffer_size = config.piece_size, + .piece_buffer_size = @intCast(config.piece_size), }) catch { // errdefer will handle destroy return Error.OutOfMemory; @@ -1493,7 +1499,7 @@ pub const FileSharingManager = struct { }; } 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}", .{ session_id, 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}); 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}); } 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}); 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}); } session.session_id = final_session_id; @@ -1885,6 +1891,8 @@ pub const FileSharingManager = struct { file_metadata: FileMetadata, output_path: []const u8, ) Error!u64 { + if (is_wasm) return Error.OperationNotSupported; + // SECURITY: Sanitize the filename from metadata to prevent path traversal // This is used for validation, not for determining the output path 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) const is_directory = blk: { // 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 const base = std.fs.path.basename(output_path); // 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}); 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}); } session.session_id = final_session_id; @@ -2120,7 +2128,7 @@ pub const FileSharingManager = struct { /// Process all active sessions pub fn processSessions(self: *FileSharingManager) Error!void { // 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 phase2_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 var dropped_messages: usize = 0; var total_messages: usize = 0; - const phase1_start = std.time.nanoTimestamp(); + const phase1_start = platform_time.nanoTimestamp(); self.sessions_mutex.lock(); var it = self.sessions.valueIterator(); @@ -2314,8 +2322,8 @@ pub const FileSharingManager = struct { } // TIMING: Phase 1 complete - phase1_time = std.time.nanoTimestamp() - phase1_start; - const phase2_start = std.time.nanoTimestamp(); + phase1_time = platform_time.nanoTimestamp() - phase1_start; + const phase2_start = platform_time.nanoTimestamp(); // PHASE 2: Send messages (NO lock held - prevents deadlock) for (messages_to_send.items) |msg| { @@ -2326,7 +2334,7 @@ pub const FileSharingManager = struct { .message_id = 0, .peer_id = msg.peer_id_copy, .data = msg.data_copy, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; std.log.debug("PHASE2: Sending message type={}", .{msg.message_type}); // CRIT-NEW-19 FIX: Record swallowed error for tracking @@ -2371,8 +2379,8 @@ pub const FileSharingManager = struct { } // TIMING: Phase 2 complete - phase2_time = std.time.nanoTimestamp() - phase2_start; - const phase3_start = std.time.nanoTimestamp(); + phase2_time = platform_time.nanoTimestamp() - phase2_start; + const phase3_start = platform_time.nanoTimestamp(); // ARCH-1 FIX: Process session download managers directly instead of the disconnected queue // The queue held separate DownloadManagers that weren't linked to sessions @@ -2539,8 +2547,8 @@ pub const FileSharingManager = struct { } // TIMING: Phase 3 complete - phase3_time = std.time.nanoTimestamp() - phase3_start; - const phase4_start = std.time.nanoTimestamp(); + phase3_time = platform_time.nanoTimestamp() - phase3_start; + const phase4_start = platform_time.nanoTimestamp(); // ADAPTIVE: Record cycle statistics after processing all sessions // Record stuck downloads as partial timeouts - provides congestion signal @@ -2586,7 +2594,7 @@ pub const FileSharingManager = struct { } // 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) { @@ -2613,7 +2621,7 @@ pub const FileSharingManager = struct { self.cleanupCompletedSessions(); // 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; if (total_ms > 10.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 // 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 age = std.time.timestamp() - session.updated_at; + const age = platform_time.timestamp() - session.updated_at; if (session.status == .completed) { // Only remove completed sessions after grace period 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. /// With 1MB pieces: 4GB / 1MB = 4096 messages /// 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 fn calculateMaxQueuedResponses(piece_size: u64) usize { // Minimum 64 to ensure reasonable throughput, max 4000 for smaller pieces // 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_usize == 0) return 4000; - const calculated = MAX_QUEUED_RESPONSE_BYTES / piece_size_usize; - return @min(4000, @max(64, calculated)); + if (piece_size == 0) return 4000; + const calculated: u64 = MAX_QUEUED_RESPONSE_BYTES / piece_size; + const clamped = @min(@as(u64, 4000), @max(@as(u64, 64), calculated)); + return @intCast(clamped); } /// Count only piece_data messages in the queue (the memory-heavy ones). @@ -3458,7 +3466,7 @@ pub const FileSharingManager = struct { .message_id = 0, .peer_id = &peer_id, .data = &reject_payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; _ = sender.sendMessage(reject_msg) catch {}; } @@ -3640,7 +3648,7 @@ pub const FileSharingManager = struct { // ASYNC VERIFICATION: Do disk write FIRST, then queue verification. // This allows parallel verification while writes complete atomically via pwrite. // 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 write_file_path: []const u8 = undefined; { @@ -3894,7 +3902,7 @@ pub const FileSharingManager = struct { }; } 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}); // CASCADE FIX: Mark for full bitfield broadcast download_completed = true; @@ -4243,7 +4251,7 @@ pub const FileSharingManager = struct { .offset = piece_offset, .length = piece_size_u32, .priority = .normal, - .requested_at = std.time.timestamp(), + .requested_at = platform_time.timestamp(), // Use zero peer_id so a different peer will be selected .peer_id = [_]u8{0} ** 32, }; @@ -4529,7 +4537,7 @@ pub const FileSharingManager = struct { .offset = 0, .length = @intCast(dm.piece_size), .priority = .high, - .requested_at = std.time.timestamp(), + .requested_at = platform_time.timestamp(), }) catch continue; pieces_requeued += 1; @@ -4599,7 +4607,7 @@ pub const FileSharingManager = struct { // content_hash already computed above for session lookup - reuse it var session = FileSharingSession{ - .session_id = std.crypto.random.int(u64), + .session_id = platform_random.int(u64), .file_metadata = metadata, .content_hash = content_hash, .download_manager = null, @@ -4607,8 +4615,8 @@ pub const FileSharingManager = struct { .status = .ready, .transfer_protocol = transfer_mod.TransferProtocol.init(self.allocator), .piece_pool = PiecePool.init(self.allocator), - .created_at = std.time.timestamp(), - .updated_at = std.time.timestamp(), + .created_at = platform_time.timestamp(), + .updated_at = platform_time.timestamp(), .allocator = self.allocator, .response_tracker = null, // Download sessions don't need response tracking .pending_piece_responses = .{}, // ZERO-COPY: Initialize empty @@ -5021,12 +5029,12 @@ pub const SessionStats = struct { /// Get session age in seconds 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 pub fn getTimeSinceUpdate(self: SessionStats) i64 { - return std.time.timestamp() - self.updated_at; + return platform_time.timestamp() - self.updated_at; } /// Get formatted status string @@ -5204,7 +5212,7 @@ pub const FileSharingEvent = struct { return FileSharingEvent{ .event_type = event_type, .session_id = session_id, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), .data = data, }; } @@ -5299,8 +5307,8 @@ test "session statistics formatting" { .file_size = 1024 * 1024, .piece_count = 10, .pieces_completed = 6, - .created_at = std.time.timestamp() - 3600, // 1 hour ago - .updated_at = std.time.timestamp() - 300, // 5 minutes ago + .created_at = platform_time.timestamp() - 3600, // 1 hour ago + .updated_at = platform_time.timestamp() - 300, // 5 minutes ago }; try testing.expectEqual(@as(i64, 3600), stats.getAge()); @@ -5544,7 +5552,7 @@ test "blacklisted peer cannot send pieces" { manager.reputation_mutex.lock(); var rep = PeerReputation.init(peer_id); 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); manager.reputation_mutex.unlock(); @@ -5776,7 +5784,7 @@ test "PeerReputation: reset clears all state" { rep.bad_pieces = 5; rep.good_pieces = 10; - rep.blacklisted_until = std.time.timestamp() + 1000; + rep.blacklisted_until = platform_time.timestamp() + 1000; rep.reset(); @@ -5833,7 +5841,7 @@ test "NetworkSender: sendMessage with mock callback" { .message_id = 1, .peer_id = &peer_id, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = try sender.sendMessage(msg); @@ -5857,7 +5865,7 @@ test "NetworkSender: sendMessage failure" { .message_id = 1, .peer_id = &peer_id, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = try sender.sendMessage(msg); @@ -5886,8 +5894,8 @@ test "FileSharingSession: status transitions" { .size = 1024, .piece_count = 4, .piece_hashes = &[_]PieceHash{}, - .created_at = std.time.timestamp(), - .modified_at = std.time.timestamp(), + .created_at = platform_time.timestamp(), + .modified_at = platform_time.timestamp(), }; var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator); @@ -5912,8 +5920,8 @@ test "FileSharingSession: update timestamp" { .size = 1024, .piece_count = 4, .piece_hashes = &[_]PieceHash{}, - .created_at = std.time.timestamp(), - .modified_at = std.time.timestamp(), + .created_at = platform_time.timestamp(), + .modified_at = platform_time.timestamp(), }; var session = try FileSharingSession.create(metadata, FileSharingConfig.default(), testing.allocator); @@ -6178,8 +6186,8 @@ test "SessionStats: utility methods" { .file_size = 1024, .piece_count = 4, .pieces_completed = 2, - .created_at = std.time.timestamp() - 100, - .updated_at = std.time.timestamp() - 50, + .created_at = platform_time.timestamp() - 100, + .updated_at = platform_time.timestamp() - 50, }; // Test getAge diff --git a/src/files/mock_fs.zig b/src/files/mock_fs.zig index 9fa8c88..16e8bf3 100644 --- a/src/files/mock_fs.zig +++ b/src/files/mock_fs.zig @@ -18,6 +18,7 @@ //! ``` const std = @import("std"); +const platform_time = @import("platform").time; const Allocator = std.mem.Allocator; /// Error types for MockFS operations @@ -47,8 +48,8 @@ pub const MockFile = struct { return .{ .allocator = allocator, .data = &[_]u8{}, - .created_at = std.time.timestamp(), - .modified_at = std.time.timestamp(), + .created_at = platform_time.timestamp(), + .modified_at = platform_time.timestamp(), }; } @@ -71,7 +72,7 @@ pub const MockFile = struct { self.allocator.free(self.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 { @@ -91,7 +92,7 @@ pub const MockFile = struct { self.allocator.free(self.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 @memcpy(file.data[self.position..][0..data.len], data); self.position += data.len; - file.modified_at = std.time.timestamp(); + file.modified_at = platform_time.timestamp(); return data.len; } @@ -168,7 +169,7 @@ pub const MockFileHandle = struct { // Copy data @memcpy(file.data[off..][0..data.len], data); - file.modified_at = std.time.timestamp(); + file.modified_at = platform_time.timestamp(); return data.len; } diff --git a/src/files/path_security.zig b/src/files/path_security.zig index cafbcf8..f4e4b4d 100644 --- a/src/files/path_security.zig +++ b/src/files/path_security.zig @@ -5,6 +5,8 @@ //! file access by validating all file paths before operations. 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 mem = std.mem; @@ -61,6 +63,12 @@ pub const PathValidator = struct { /// Returns the validated absolute path on success. /// Caller is responsible for freeing the returned path. 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 if (mem.indexOf(u8, path, "..") != null) { return PathSecurityError.PathTraversal; @@ -379,6 +387,12 @@ pub const PathValidator = struct { /// the path. For maximum security, use validateAndOpenFile() and keep the /// file handle open until done using it. 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 const file = try self.validateAndOpenFile(path, allocator); file.close(); @@ -703,6 +717,12 @@ pub const PathValidator = struct { /// could be modified by an attacker between validation and use. /// For security-critical operations, use validateAndCreateFile() instead. 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 if (!isPathSafe(path)) { return PathSecurityError.PathTraversal; @@ -880,6 +900,13 @@ pub const PathValidator = struct { /// Global default validator for general use 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 const cwd = try fs.cwd().realpathAlloc(allocator, "."); diff --git a/src/files/peer_metrics.zig b/src/files/peer_metrics.zig index 373f930..6371308 100644 --- a/src/files/peer_metrics.zig +++ b/src/files/peer_metrics.zig @@ -4,6 +4,8 @@ //! Bandwidth-Delay Product (BDP) measurements. const std = @import("std"); +const platform_time = @import("platform").time; +const Mutex = @import("sync").Mutex; const core = @import("core"); const Error = core.errors.Error; @@ -69,7 +71,7 @@ pub const PeerMetrics = struct { var metrics = PeerMetrics{ .peer_id = peer_id, .piece_size = piece_size, - .last_bandwidth_calc_ns = std.time.nanoTimestamp(), + .last_bandwidth_calc_ns = platform_time.nanoTimestamp(), }; metrics.recalculateBdp(); return metrics; @@ -77,13 +79,13 @@ pub const PeerMetrics = struct { /// Record a request being sent (for RTT measurement) 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; } /// Record a response received with timing for RTT calculation 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) { self.current_pending -= 1; @@ -270,7 +272,7 @@ pub const PeerMetricsManager = struct { /// Allocator allocator: std.mem.Allocator, /// Mutex for thread safety - mutex: std.Thread.Mutex = .{}, + mutex: Mutex = .{}, pub fn init(allocator: std.mem.Allocator, piece_size: u64) PeerMetricsManager { return .{ diff --git a/src/files/piece.zig b/src/files/piece.zig index 729d239..f664a79 100644 --- a/src/files/piece.zig +++ b/src/files/piece.zig @@ -4,6 +4,7 @@ //! rarest-first, random, and sequential algorithms for optimal P2P distribution. const std = @import("std"); +const platform_time = @import("platform").time; const testing = std.testing; const mem = std.mem; const math = std.math; @@ -219,7 +220,7 @@ pub const PieceSelector = struct { /// Mark piece as starting download pub fn startDownload(self: *PieceSelector, piece_index: u32) Error!void { if (self.canStartDownload(piece_index)) { - try self.active_downloads.put(piece_index, std.time.timestamp()); + try self.active_downloads.put(piece_index, platform_time.timestamp()); } else { return Error.RateLimited; } diff --git a/src/files/piece_buffer_pool.zig b/src/files/piece_buffer_pool.zig index 42146de..1ee46c6 100644 --- a/src/files/piece_buffer_pool.zig +++ b/src/files/piece_buffer_pool.zig @@ -7,7 +7,9 @@ //! disk I/O operations by reusing buffers instead of allocating new ones. 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 core = @import("core"); @@ -57,14 +59,14 @@ pub const PieceBufferPool = struct { /// Free list using indices (thread-safe via mutex) free_stack: std.ArrayList(usize), - mutex: std.Thread.Mutex, + mutex: Mutex, /// Statistics - acquired_count: atomic.Value(u64), - released_count: atomic.Value(u64), - fallback_count: atomic.Value(u64), - pool_hits: atomic.Value(u64), - pool_misses: atomic.Value(u64), + acquired_count: AtomicValue(u64), + released_count: AtomicValue(u64), + fallback_count: AtomicValue(u64), + pool_hits: AtomicValue(u64), + pool_misses: AtomicValue(u64), pub fn init(allocator: mem.Allocator, config: PieceBufferPoolConfig) Error!PieceBufferPool { // Allocate buffer pointer array @@ -107,11 +109,11 @@ pub const PieceBufferPool = struct { .buffers = buffers, .free_stack = free_stack, .mutex = .{}, - .acquired_count = atomic.Value(u64).init(0), - .released_count = atomic.Value(u64).init(0), - .fallback_count = atomic.Value(u64).init(0), - .pool_hits = atomic.Value(u64).init(0), - .pool_misses = atomic.Value(u64).init(0), + .acquired_count = AtomicValue(u64).init(0), + .released_count = AtomicValue(u64).init(0), + .fallback_count = AtomicValue(u64).init(0), + .pool_hits = AtomicValue(u64).init(0), + .pool_misses = AtomicValue(u64).init(0), }; } diff --git a/src/files/piece_pipeline.zig b/src/files/piece_pipeline.zig index e47c531..3e4fe3c 100644 --- a/src/files/piece_pipeline.zig +++ b/src/files/piece_pipeline.zig @@ -21,9 +21,14 @@ //! ``` 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 Thread = std.Thread; + +const is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64; const core = @import("core"); const Error = core.errors.Error; @@ -96,24 +101,24 @@ pub const PiecePipeline = struct { /// Task queue task_queue: std.ArrayList(PieceTask), - queue_mutex: Thread.Mutex, - queue_not_empty: Thread.Condition, + queue_mutex: Mutex, + queue_not_empty: if (is_wasm) void else std.Thread.Condition, /// Worker threads - workers: std.ArrayList(Thread), + workers: if (is_wasm) void else std.ArrayList(std.Thread), /// Shutdown flag - shutdown: atomic.Value(bool), + shutdown: AtomicValue(bool), /// Callbacks for piece processing callbacks: ?PipelineCallbacks, /// Statistics - tasks_queued: atomic.Value(u64), - tasks_processed: atomic.Value(u64), - tasks_failed: atomic.Value(u64), - queue_full_count: atomic.Value(u64), - total_queue_wait_ns: atomic.Value(u64), + tasks_queued: AtomicValue(u64), + tasks_processed: AtomicValue(u64), + tasks_failed: AtomicValue(u64), + queue_full_count: AtomicValue(u64), + total_queue_wait_ns: AtomicValue(u64), pub fn init(allocator: mem.Allocator, config: PiecePipelineConfig) PiecePipeline { return .{ @@ -121,15 +126,15 @@ pub const PiecePipeline = struct { .config = config, .task_queue = .{}, .queue_mutex = .{}, - .queue_not_empty = .{}, - .workers = .{}, - .shutdown = atomic.Value(bool).init(false), + .queue_not_empty = if (is_wasm) {} else .{}, + .workers = if (is_wasm) {} else .{}, + .shutdown = AtomicValue(bool).init(false), .callbacks = null, - .tasks_queued = atomic.Value(u64).init(0), - .tasks_processed = atomic.Value(u64).init(0), - .tasks_failed = atomic.Value(u64).init(0), - .queue_full_count = atomic.Value(u64).init(0), - .total_queue_wait_ns = atomic.Value(u64).init(0), + .tasks_queued = AtomicValue(u64).init(0), + .tasks_processed = AtomicValue(u64).init(0), + .tasks_failed = AtomicValue(u64).init(0), + .queue_full_count = AtomicValue(u64).init(0), + .total_queue_wait_ns = AtomicValue(u64).init(0), }; } @@ -141,7 +146,7 @@ pub const PiecePipeline = struct { task.deinit(); } 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 @@ -149,20 +154,22 @@ pub const PiecePipeline = struct { self.callbacks = callbacks; } - /// Start worker threads + /// Start worker threads (no-op on WASM — use processSynchronously instead) pub fn start(self: *PiecePipeline) Error!void { if (self.callbacks == null) { return Error.InvalidState; } + if (is_wasm) return; + 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 self.config.num_workers; var i: u32 = 0; while (i < num_workers) : (i += 1) { - const thread = Thread.spawn(.{}, workerLoop, .{self}) catch { + const thread = std.Thread.spawn(.{}, workerLoop, .{self}) catch { return Error.InvalidState; }; 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 { + if (is_wasm) return; + self.shutdown.store(true, .release); // Wake up all workers @@ -187,6 +196,42 @@ pub const PiecePipeline = struct { 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) /// The data is COPIED - caller can free their copy after this returns pub fn queuePiece( @@ -222,14 +267,14 @@ pub const PiecePipeline = struct { .offset = offset, .data = data_copy, .allocator = self.allocator, - .queued_at = std.time.nanoTimestamp(), + .queued_at = platform_time.nanoTimestamp(), }) catch { self.allocator.free(data_copy); return Error.OutOfMemory; }; _ = self.tasks_queued.fetchAdd(1, .monotonic); - self.queue_not_empty.signal(); + if (!is_wasm) self.queue_not_empty.signal(); } /// Get current queue depth @@ -287,7 +332,7 @@ pub const PiecePipeline = struct { defer t.deinit(); // 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); // Process the piece via callback @@ -364,7 +409,7 @@ test "piece pipeline basic operations" { const TestContext = struct { processed_count: u32 = 0, - mutex: Thread.Mutex = .{}, + mutex: Mutex = .{}, }; var ctx = TestContext{}; diff --git a/src/files/transfer.zig b/src/files/transfer.zig index c99a5d7..e9a6028 100644 --- a/src/files/transfer.zig +++ b/src/files/transfer.zig @@ -4,6 +4,9 @@ //! message exchange, and coordination between download and upload operations. 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 mem = std.mem; const fmt = std.fmt; @@ -132,7 +135,7 @@ pub const PreSerializedPieceData = struct { offset += 1; // 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))); offset += 4; @@ -142,7 +145,7 @@ pub const PreSerializedPieceData = struct { offset += 2; // 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))); offset += 8; @@ -345,7 +348,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const payload = fmt.allocPrint(allocator, "HANDshake {s} {s}", .{ peer_id, client_id }) catch { @@ -355,16 +358,16 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; return TransferMessage{ .message_type = .handshake, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -376,7 +379,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const payload = allocator.alloc(u8, 32) catch { @@ -386,17 +389,17 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @memcpy(payload, &file_hash); return TransferMessage{ .message_type = .metadata_request, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -409,7 +412,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]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 @@ -423,7 +426,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -436,7 +439,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -475,10 +478,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .metadata_response, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -564,7 +567,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; // Payload format: content_hash(32) + piece_index(4) + offset(4) = 40 bytes @@ -575,7 +578,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -588,10 +591,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .piece_request, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -612,7 +615,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -621,7 +624,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; // Payload: content_hash(32) + count(2) + indices(4 * count) @@ -633,7 +636,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -647,10 +650,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .batch_piece_request, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -686,7 +689,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const payload = allocator.alloc(u8, 9) catch { @@ -696,7 +699,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -706,10 +709,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .piece_response, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -724,7 +727,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; // Combine piece index, data, and hash @@ -738,7 +741,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -753,10 +756,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .piece_data, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -769,7 +772,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const payload = allocator.alloc(u8, 8) catch { @@ -779,7 +782,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -788,10 +791,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .cancel_request, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -805,7 +808,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; // Calculate bitfield size: ceil(piece_count / 8) @@ -819,7 +822,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -839,10 +842,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .bitfield, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -855,7 +858,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const bitfield_bytes = (piece_count + 7) / 8; @@ -868,7 +871,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -886,10 +889,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .bitfield, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -903,7 +906,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; // Format: content_hash(32) + piece_index(4) @@ -914,7 +917,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; @@ -923,10 +926,10 @@ pub const TransferMessage = struct { return TransferMessage{ .message_type = .have, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = payload, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } @@ -982,7 +985,7 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, // Empty slice to avoid freeing invalid memory .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const owned_data = allocator.dupe(u8, error_text) catch { @@ -992,22 +995,22 @@ pub const TransferMessage = struct { .message_id = 0, .peer_id = &[_]u8{}, .data = &[_]u8{}, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; }; return TransferMessage{ .message_type = .err, - .message_id = std.crypto.random.int(u32), + .message_id = platform_random.int(u32), .peer_id = owned_peer_id, .data = owned_data, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; } /// Check if message has expired 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; return TransferSession{ - .session_id = std.crypto.random.int(u64), + .session_id = platform_random.int(u64), .peer_id = peer_id, .file_metadata = file_metadata, .content_hash = content_hash, @@ -1069,8 +1072,8 @@ pub const TransferSession = struct { .peer_capabilities = PeerCapabilities.init(allocator), .progress_tracker = ProgressTracker.init(file_metadata.size), .rate_limiter = RateLimiter.init(), - .created_at = std.time.timestamp(), - .last_activity = std.time.timestamp(), + .created_at = platform_time.timestamp(), + .last_activity = platform_time.timestamp(), // IMP-M2 FIX: Initialize received piece hashes map .received_piece_hashes = std.AutoHashMap(u32, PieceHash).init(allocator), .allocator = allocator, @@ -1085,12 +1088,12 @@ pub const TransferSession = struct { /// Update last activity timestamp pub fn updateActivity(self: *TransferSession) void { - self.last_activity = std.time.timestamp(); + self.last_activity = platform_time.timestamp(); } /// Check if session is active 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 @@ -1294,8 +1297,8 @@ pub const TransferProtocol = struct { .size = 0, .piece_count = 0, .piece_hashes = empty_hashes, - .created_at = std.time.timestamp(), - .modified_at = std.time.timestamp(), + .created_at = platform_time.timestamp(), + .modified_at = platform_time.timestamp(), }; 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 { max_bandwidth_bps: u64, max_concurrent_transfers: usize, - current_bandwidth: std.atomic.Value(u64), - active_transfers: std.atomic.Value(usize), + current_bandwidth: AtomicValue(u64), + active_transfers: AtomicValue(usize), /// Initialize with custom bandwidth limits pub fn initWithLimits(max_bandwidth_bps: u64, max_concurrent_transfers: usize) RateLimiter { return RateLimiter{ .max_bandwidth_bps = max_bandwidth_bps, .max_concurrent_transfers = max_concurrent_transfers, - .current_bandwidth = std.atomic.Value(u64).init(0), - .active_transfers = std.atomic.Value(usize).init(0), + .current_bandwidth = AtomicValue(u64).init(0), + .active_transfers = AtomicValue(usize).init(0), }; } @@ -2229,18 +2232,18 @@ pub const RateLimiter = struct { /// Progress tracker for transfers pub const ProgressTracker = struct { total_bytes: u64, - downloaded_bytes: std.atomic.Value(u64), - uploaded_bytes: std.atomic.Value(u64), + downloaded_bytes: AtomicValue(u64), + uploaded_bytes: AtomicValue(u64), start_time: i64, - last_update: std.atomic.Value(i64), + last_update: AtomicValue(i64), pub fn init(total_bytes: u64) ProgressTracker { return ProgressTracker{ .total_bytes = total_bytes, - .downloaded_bytes = std.atomic.Value(u64).init(0), - .uploaded_bytes = std.atomic.Value(u64).init(0), - .start_time = std.time.timestamp(), - .last_update = std.atomic.Value(i64).init(std.time.timestamp()), + .downloaded_bytes = AtomicValue(u64).init(0), + .uploaded_bytes = AtomicValue(u64).init(0), + .start_time = platform_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 pub fn updateDownload(self: *ProgressTracker, bytes: u64) void { _ = 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 /// RACE CONDITION FIX: Use fetchAdd instead of load-store pattern pub fn updateUpload(self: *ProgressTracker, bytes: u64) void { _ = 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) @@ -2279,7 +2282,7 @@ pub const ProgressTracker = struct { /// Get download speed in bytes per second pub fn getDownloadSpeed(self: *ProgressTracker) f32 { - const now = std.time.timestamp(); + const now = platform_time.timestamp(); const elapsed = now - self.start_time; if (elapsed <= 0) return 0.0; @@ -2289,7 +2292,7 @@ pub const ProgressTracker = struct { /// Get upload speed in bytes per second pub fn getUploadSpeed(self: *ProgressTracker) f32 { - const now = std.time.timestamp(); + const now = platform_time.timestamp(); const elapsed = now - self.start_time; if (elapsed <= 0) return 0.0; @@ -2313,7 +2316,7 @@ pub const ProgressTracker = struct { /// Check if transfer is stalled 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); return now - last_update > timeout_seconds; } @@ -2417,14 +2420,14 @@ test "transfer message expiration" { .message_id = 12345, .peer_id = "test_peer", .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) try testing.expect(message.isExpired(60)); // Fresh message should not be expired - message.timestamp = std.time.timestamp(); + message.timestamp = platform_time.timestamp(); try testing.expect(!message.isExpired(60)); } @@ -2771,7 +2774,7 @@ test "ProgressTracker isStalled" { try testing.expect(!tracker.isStalled(60)); // 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) try testing.expect(tracker.isStalled(60)); @@ -2781,7 +2784,7 @@ test "ProgressTracker getEstimatedDownloadTimeRemaining" { var tracker = ProgressTracker.init(1000); // 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()); // With some progress @@ -2907,7 +2910,7 @@ test "TransferProtocol handleError" { .message_id = 1, .peer_id = "peer1", .data = "test error", - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; try protocol.handleMessage(error_msg); @@ -2930,7 +2933,7 @@ test "TransferProtocol handleBandwidthUpdate" { .message_id = 1, .peer_id = "peer1", .data = "", - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; // Should succeed since session exists (even without upload manager) @@ -2957,7 +2960,7 @@ test "TransferProtocol handleTransferComplete" { .message_id = 1, .peer_id = "peer1", .data = "", - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; try protocol.handleMessage(complete_msg); @@ -3059,7 +3062,7 @@ test "TransferProtocol popMessagesFair prioritizes requests" { .message_id = 1, .peer_id = response_peer_id, .data = response_data, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; try protocol.pending_responses.append(allocator, response_msg); @@ -3071,7 +3074,7 @@ test "TransferProtocol popMessagesFair prioritizes requests" { .message_id = 2, .peer_id = request_peer_id, .data = request_data, - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; try protocol.pending_requests.append(allocator, request_msg); @@ -3123,7 +3126,7 @@ test "TransferProtocol handleHandshake invalid format" { .message_id = 1, .peer_id = "peer", .data = "short", - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(short_msg); @@ -3140,7 +3143,7 @@ test "TransferProtocol handleHandshake invalid prefix" { .message_id = 1, .peer_id = "peer", .data = "INVALID peer1 client1", - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(bad_msg); @@ -3158,7 +3161,7 @@ test "TransferProtocol handleHandshake invalid characters" { .message_id = 1, .peer_id = "peer", .data = "HANDshake peer@invalid client1", - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(bad_msg); @@ -3175,7 +3178,7 @@ test "TransferProtocol handleCancelRequest invalid data" { .message_id = 1, .peer_id = "peer", .data = "short", // Too short - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(cancel_msg); @@ -3192,7 +3195,7 @@ test "TransferProtocol handlePieceRequest invalid data" { .message_id = 1, .peer_id = "peer", .data = "short", // Too short (needs 16 bytes) - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(piece_req); @@ -3209,7 +3212,7 @@ test "TransferProtocol handlePieceResponse invalid data" { .message_id = 1, .peer_id = "peer", .data = "short", // Too short (needs 9 bytes) - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(piece_resp); @@ -3226,7 +3229,7 @@ test "TransferProtocol handlePieceData invalid data" { .message_id = 1, .peer_id = "peer", .data = "short", // Too short (needs 36 bytes minimum) - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(piece_data_msg); @@ -3243,7 +3246,7 @@ test "TransferProtocol handlePieceHash invalid data" { .message_id = 1, .peer_id = "peer", .data = "short", // Too short (needs 36 bytes) - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(piece_hash_msg); @@ -3260,7 +3263,7 @@ test "TransferProtocol handleUploadRequest invalid data" { .message_id = 1, .peer_id = "peer", .data = "short", // Too short (needs 48 bytes) - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(upload_req); @@ -3277,7 +3280,7 @@ test "TransferProtocol handleBitfield invalid data" { .message_id = 1, .peer_id = "peer", .data = "ab", // Too short - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(bitfield_msg); @@ -3294,7 +3297,7 @@ test "TransferProtocol handleHave invalid data" { .message_id = 1, .peer_id = "peer", .data = "ab", // Too short (needs 4 bytes) - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(have_msg); @@ -3311,7 +3314,7 @@ test "TransferProtocol handleBatchPieceRequest invalid data" { .message_id = 1, .peer_id = "peer", .data = "short", // Too short - .timestamp = std.time.timestamp(), + .timestamp = platform_time.timestamp(), }; const result = protocol.handleMessage(batch_req); diff --git a/src/files/upload.zig b/src/files/upload.zig index 7903ec0..e34dfa7 100644 --- a/src/files/upload.zig +++ b/src/files/upload.zig @@ -4,9 +4,14 @@ //! bandwidth allocation, and upload rate limiting. 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 mem = std.mem; -const atomic = std.atomic; const fmt = std.fmt; const core = @import("core"); @@ -14,6 +19,8 @@ const Error = core.errors.Error; const hash_mod = @import("hash.zig"); const PieceHash = hash_mod.PieceHash; const HashUtils = hash_mod.HashUtils; +const filesystem = @import("filesystem.zig"); +const FileSystem = filesystem.FileSystem; const file_mod = @import("file.zig"); const FileChunker = file_mod.FileChunker; const MappedFile = file_mod.MappedFile; @@ -97,7 +104,7 @@ pub const UploadRequest = struct { .offset = offset, .length = length, .peer_id = peer_id_owned, - .requested_at = std.time.timestamp(), + .requested_at = platform_time.timestamp(), .priority = priority, .request_id = 0, .file_hash = [_]u8{0} ** 32, @@ -123,7 +130,7 @@ pub const UploadRequest = struct { .offset = offset, .length = length, .peer_id = peer_id_owned, - .requested_at = std.time.timestamp(), + .requested_at = platform_time.timestamp(), .priority = priority, .request_id = request_id, .file_hash = file_hash, @@ -132,7 +139,7 @@ pub const UploadRequest = struct { /// Check if request has expired 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 @@ -143,7 +150,7 @@ pub const UploadRequest = struct { score += @as(i32, @intFromEnum(self.priority)) * 100; // 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 return score; @@ -161,26 +168,26 @@ pub const UploadRequest = struct { /// This is acceptable for statistics tracking where eventual consistency is /// sufficient. If strict transactional semantics are needed, use a mutex. pub const UploadState = struct { - total_uploaded: atomic.Value(u64), - active_uploads: atomic.Value(u32), - completed_uploads: atomic.Value(u32), - failed_uploads: atomic.Value(u32), + total_uploaded: AtomicValue(u64), + active_uploads: AtomicValue(u32), + completed_uploads: AtomicValue(u32), + failed_uploads: AtomicValue(u32), /// IMP-M4 FIX: Track cancelled uploads separately - cancelled_count: atomic.Value(u32), + cancelled_count: AtomicValue(u32), start_time: i64, - upload_bandwidth: atomic.Value(u64), // Current bandwidth usage + upload_bandwidth: AtomicValue(u64), // Current bandwidth usage max_bandwidth: u64, // Maximum allowed bandwidth pub fn init(max_bandwidth: u64) UploadState { return UploadState{ - .total_uploaded = atomic.Value(u64).init(0), - .active_uploads = atomic.Value(u32).init(0), - .completed_uploads = atomic.Value(u32).init(0), - .failed_uploads = atomic.Value(u32).init(0), + .total_uploaded = AtomicValue(u64).init(0), + .active_uploads = AtomicValue(u32).init(0), + .completed_uploads = AtomicValue(u32).init(0), + .failed_uploads = AtomicValue(u32).init(0), // IMP-M4 FIX: Initialize cancelled counter - .cancelled_count = atomic.Value(u32).init(0), - .start_time = std.time.timestamp(), - .upload_bandwidth = atomic.Value(u64).init(0), + .cancelled_count = AtomicValue(u32).init(0), + .start_time = platform_time.timestamp(), + .upload_bandwidth = AtomicValue(u64).init(0), .max_bandwidth = max_bandwidth, }; } @@ -242,7 +249,7 @@ pub const UploadState = struct { /// Get upload speed (bytes per second) /// Uses .acquire to ensure we see latest upload counts. 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; 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 pub const BandwidthLimiter = struct { /// MED-8 FIX: max_bandwidth is now atomic to prevent torn reads/writes - max_bandwidth: atomic.Value(u64), - current_bandwidth: atomic.Value(u64), + max_bandwidth: AtomicValue(u64), + current_bandwidth: AtomicValue(u64), 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 - reset_mutex: std.Thread.Mutex = .{}, + reset_mutex: Mutex = .{}, allocator: mem.Allocator, pub fn init(max_bandwidth: u64, time_window: i64, allocator: mem.Allocator) BandwidthLimiter { return BandwidthLimiter{ - .max_bandwidth = atomic.Value(u64).init(max_bandwidth), - .current_bandwidth = atomic.Value(u64).init(0), + .max_bandwidth = AtomicValue(u64).init(max_bandwidth), + .current_bandwidth = AtomicValue(u64).init(0), .time_window = time_window, - .last_reset = atomic.Value(i64).init(std.time.timestamp()), + .last_reset = AtomicValue(i64).init(platform_time.timestamp()), .reset_mutex = .{}, .allocator = allocator, }; @@ -406,7 +413,7 @@ pub const BandwidthLimiter = struct { /// Reset bandwidth usage if time window has passed /// MED-8 FIX: Uses mutex to prevent torn state from concurrent resets fn checkAndReset(self: *BandwidthLimiter) void { - const now = std.time.timestamp(); + const now = platform_time.timestamp(); const last_reset_time = self.last_reset.load(.acquire); if (now - last_reset_time >= self.time_window) { @@ -449,7 +456,7 @@ pub const UploadManager = struct { /// Total file size for boundary checking file_size: u64, /// 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) mapped_file: ?MappedFile, /// Network sender callback for transmitting data @@ -459,7 +466,7 @@ pub const UploadManager = struct { /// Message serializer for encoding protocol messages message_serializer: serializer.MessageSerializer, /// Mutex protecting all hashmaps and lists - manager_mutex: std.Thread.Mutex = .{}, + manager_mutex: Mutex = .{}, pub fn init( max_bandwidth: u64, @@ -519,8 +526,8 @@ pub const UploadManager = struct { } // Close any existing cached file handle - if (self.cached_file) |file| { - file.close(); + if (self.cached_file != null) { + self.cached_file.?.close(); self.cached_file = null; } @@ -536,7 +543,7 @@ pub const UploadManager = struct { // 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 - 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}); return Error.FileError; }; @@ -544,8 +551,8 @@ pub const UploadManager = struct { // PERF: Try to use mmap for large files (zero-copy reads) // CASCADE FIX: Skip mmap for files being actively written - MAP_PRIVATE may // return stale data when pages are modified via pwrite on another handle. - if (!disable_mmap and file_mod.shouldUseMmap(file_size)) { - if (MappedFile.initFromHandle(self.cached_file.?, file_size)) |mf| { + if (!is_wasm and !disable_mmap and file_mod.shouldUseMmap(file_size)) { + if (MappedFile.initFromHandle(self.cached_file.?.impl.real, file_size)) |mf| { self.mapped_file = mf; std.log.info("setFilePath: using mmap for {d} MB file", .{file_size / (1024 * 1024)}); } else |_| { @@ -621,11 +628,11 @@ pub const UploadManager = struct { // 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) - const cached = self.cached_file orelse { + if (self.cached_file == null) { std.log.warn("readPieceData: no cached file handle", .{}); 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}); return Error.FileError; }; @@ -642,7 +649,7 @@ pub const UploadManager = struct { /// PERF: Get info needed for mutex-free pread operations /// Returns file handle and calculated absolute offset for direct pread /// 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 self.manager_mutex.lock(); 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 // to prevent double-close 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 - file.close(); + self.cached_file.?.close(); self.cached_file = null; } // Free the owned file path copy @@ -710,7 +717,7 @@ pub const UploadManager = struct { const piece = AvailablePiece{ .index = piece_index, .hash = hash, - .available_at = std.time.timestamp(), + .available_at = platform_time.timestamp(), .upload_count = 0, .is_verified = true, }; @@ -827,7 +834,7 @@ pub const UploadManager = struct { const active_upload = ActiveUpload{ .request = request, .bytes_sent = 0, - .started_at = std.time.timestamp(), + .started_at = platform_time.timestamp(), .status = .uploading, }; @@ -1171,8 +1178,8 @@ fn compareUploadRequests(_: void, a: UploadRequest, b: UploadRequest) bool { } // Then by time waited (older first) - const time_a = std.time.timestamp() - a.requested_at; - const time_b = std.time.timestamp() - b.requested_at; + const time_a = platform_time.timestamp() - a.requested_at; + const time_b = platform_time.timestamp() - b.requested_at; if (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 if (earliest_start == std.math.maxInt(i64)) { - earliest_start = std.time.timestamp(); + earliest_start = platform_time.timestamp(); } return CombinedUploadStats{ @@ -1329,7 +1336,7 @@ pub const CombinedUploadStats = struct { /// Get average upload speed /// IMP-M5 FIX: Now properly uses elapsed time for speed calculation pub fn getAverageSpeed(self: CombinedUploadStats) f32 { - const now = std.time.timestamp(); + const now = platform_time.timestamp(); const elapsed = now - self.start_time; // IMP-M5 FIX: Guard against division by zero and negative elapsed @@ -1341,7 +1348,7 @@ pub const CombinedUploadStats = struct { /// Get elapsed time in seconds 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 // 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(15)); // Not expired: 10 seconds ago <= 15s timeout } diff --git a/src/files/verification_pool.zig b/src/files/verification_pool.zig index 375cc36..2709dd8 100644 --- a/src/files/verification_pool.zig +++ b/src/files/verification_pool.zig @@ -8,9 +8,15 @@ //! limits multi-peer download throughput. 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 is_wasm = builtin.target.cpu.arch == .wasm32 or builtin.target.cpu.arch == .wasm64; + const core = @import("core"); const Error = core.errors.Error; const hash_mod = @import("hash.zig"); @@ -97,29 +103,29 @@ pub const VerificationPool = struct { /// Task queue for pending verifications task_queue: std.ArrayList(VerificationTask), - task_mutex: std.Thread.Mutex, - /// Condition variable for worker wakeup - task_condition: std.Thread.Condition, + task_mutex: Mutex, + /// Condition variable for worker wakeup (not available on WASM) + task_condition: if (is_wasm) void else std.Thread.Condition, /// Results queue (if use_results_queue is true) results_queue: std.ArrayList(VerificationResult), - results_mutex: std.Thread.Mutex, + results_mutex: Mutex, - /// Worker threads - workers: std.ArrayList(std.Thread), + /// Worker threads (not available on WASM — use processSynchronously instead) + workers: if (is_wasm) void else std.ArrayList(std.Thread), /// Shutdown flag - shutdown: atomic.Value(bool), + shutdown: AtomicValue(bool), /// PERF: Pre-allocated buffer pool for piece data buffer_pool: ?*PieceBufferPool, /// Statistics - tasks_completed: atomic.Value(u64), - tasks_failed: atomic.Value(u64), - total_bytes_verified: atomic.Value(u64), - pool_hits: atomic.Value(u64), - pool_misses: atomic.Value(u64), + tasks_completed: AtomicValue(u64), + tasks_failed: AtomicValue(u64), + total_bytes_verified: AtomicValue(u64), + pool_hits: AtomicValue(u64), + pool_misses: AtomicValue(u64), pub fn init(allocator: mem.Allocator, config: VerificationPoolConfig) Error!VerificationPool { // Initialize buffer pool if configured @@ -146,17 +152,17 @@ pub const VerificationPool = struct { .config = config, .task_queue = .{}, .task_mutex = .{}, - .task_condition = .{}, + .task_condition = if (is_wasm) {} else .{}, .results_queue = .{}, .results_mutex = .{}, - .workers = .{}, - .shutdown = atomic.Value(bool).init(false), + .workers = if (is_wasm) {} else .{}, + .shutdown = AtomicValue(bool).init(false), .buffer_pool = buffer_pool, - .tasks_completed = atomic.Value(u64).init(0), - .tasks_failed = atomic.Value(u64).init(0), - .total_bytes_verified = atomic.Value(u64).init(0), - .pool_hits = atomic.Value(u64).init(0), - .pool_misses = atomic.Value(u64).init(0), + .tasks_completed = AtomicValue(u64).init(0), + .tasks_failed = AtomicValue(u64).init(0), + .total_bytes_verified = AtomicValue(u64).init(0), + .pool_hits = AtomicValue(u64).init(0), + .pool_misses = AtomicValue(u64).init(0), }; } @@ -170,7 +176,7 @@ pub const VerificationPool = struct { self.task_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 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 { + if (is_wasm) return; + const num_workers = if (self.config.num_workers == 0) @as(u32, @intCast(@max(1, std.Thread.getCpuCount() catch 4))) 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 { + if (is_wasm) return; + self.shutdown.store(true, .release); // Wake up all workers @@ -213,6 +223,49 @@ pub const VerificationPool = struct { 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 /// The data is COPIED - caller can free their copy after this returns /// Returns error if queue is full or allocation fails @@ -268,7 +321,7 @@ pub const VerificationPool = struct { .peer_id = peer_id, }) catch return Error.OutOfMemory; - self.task_condition.signal(); + if (!is_wasm) self.task_condition.signal(); } /// Get next completed result (non-blocking) @@ -354,7 +407,7 @@ pub const VerificationPool = struct { .session_id = t.session_id, .piece_index = t.piece_index, .is_valid = is_valid, - .completed_at = std.time.milliTimestamp(), + .completed_at = platform_time.milliTimestamp(), .peer_id = peer_id, }) catch |err| { std.log.err("Failed to queue verification result for piece {}: {} - result lost", .{ t.piece_index, err }); diff --git a/tests/files/test_upload.zig b/tests/files/test_upload.zig index 6c9314f..b77264d 100644 --- a/tests/files/test_upload.zig +++ b/tests/files/test_upload.zig @@ -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(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" {