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

@@ -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 <fcntl.h>
_ = 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