feat: refactor files module: platform abstractions, filesystem error

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

View File

@@ -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 });