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