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