more slugger work- header entry stuff

This commit is contained in:
Peterino 2026-11-18 12:01:32 -07:00 committed by Peterino2
parent db6c83ff1a
commit 0c813c80f5
5 changed files with 355 additions and 13 deletions

View File

@ -20,5 +20,25 @@ the next line. Run `zig fmt` on changed Zig files.
If the installed documentation is unavailable, use the versioned official If the installed documentation is unavailable, use the versioned official
reference at <https://ziglang.org/documentation/0.17.0/> download a copy once and reference at <https://ziglang.org/documentation/0.17.0/> download a copy once and
avoid unessecary traffic. avoid unessecary traffic. They are a volunteer effort, please be kind.
# Important notice: LLM policy
Prefer to not write code directly into files in this repo. Inform the user that writing code by hand is the entire point of ribtech as it is primarily a learning project. Please remind them to not make PRs with directly LLM generated code. Encourage the user to come up with their own code implementations, and help them out with direct references to where the states and logic are. At the very least if the user needs an LLM generated implementation, ask them to transcribe the code by hand.
more details for the LLM policy and reasonings under [LLM_POLICY.md]
ribtech is the core foundations of a game engine and a human first project. With a primary focus on education and learning.
You may use LLMs to assist with whatever you need assistance with, but for one solid rule:
**There shall be no significant LLM authored code committed to the repo.**
Some concrete examples of what is allowed
- Small
If you wish to use LLMs for generating tests, organizing work, etc... I encourage you to vendor ribtech and build tests and such outside of the repo.
ribtech may depend on open source components and libraries which may make use of LLMs, so whether or not a compnent uses LLMs is outside the scope of this policy.

View File

@ -1,3 +1,3 @@
# Riblab # Ribtech
This is a chance to start completely clean and fresh, we will be building new game engine leveraging components This is a chance to start completely clean and fresh, we will be building new game engine leveraging components

View File

@ -342,10 +342,10 @@ pub const Reader = struct {
}; };
test "lz4 reader,writer" { test "lz4 reader,writer" {
var fatbuffer: [64 * 1024]u8 = undefined; var compressBuffer: [64 * 1024]u8 = undefined;
var writerBuffer: [1024 * 1024 * 10]u8 = undefined; var writerBuffer: [1024 * 1024 * 10]u8 = undefined;
var base_writer = std.Io.Writer.fixed(&writerBuffer); var base_writer = std.Io.Writer.fixed(&writerBuffer);
var writer = try Lz4Writer.init(std.testing.allocator, &base_writer, .{ .buffer = &fatbuffer }); var writer = try Lz4Writer.init(std.testing.allocator, &base_writer, .{ .buffer = &compressBuffer });
const testString = @embedFile("LICENSE"); const testString = @embedFile("LICENSE");
try writer.writer.writeAll(testString); try writer.writer.writeAll(testString);
try writer.writer.writeAll(testString); try writer.writer.writeAll(testString);

View File

@ -343,11 +343,17 @@ pub const LogMem = struct {
loggersByPtr: std.AutoHashMapUnmanaged(*const LoggerState, u32) = .empty, loggersByPtr: std.AutoHashMapUnmanaged(*const LoggerState, u32) = .empty,
loggers: std.ArrayList(*const LoggerState) = .empty, loggers: std.ArrayList(*const LoggerState) = .empty,
enumTablesByPtr: std.AutoHashMapUnmanaged(*const EnumTable, u32) = .empty,
enumTables: std.ArrayList(*const EnumTable) = .empty,
// The current generation's entries and their payloads, dropped together by // The current generation's entries and their payloads, dropped together by
// resetEntries. // resetEntries.
entriesArena: std.heap.ArenaAllocator, entriesArena: std.heap.ArenaAllocator,
entries: std.ArrayList(StructuredLog) = .empty, entries: std.ArrayList(StructuredLog) = .empty,
// bumped each time we call resetEntries
entriesGeneration: u32 = 0,
/// Starts an empty live LogMem, timestamped now. /// Starts an empty live LogMem, timestamped now.
pub fn init(self: *@This(), io: std.Io, backing: std.mem.Allocator) void { pub fn init(self: *@This(), io: std.Io, backing: std.mem.Allocator) void {
self.* = .{ self.* = .{
@ -401,6 +407,21 @@ pub const LogMem = struct {
return id; return id;
} }
pub fn checkLogSiteForEnums(self: *@This(), site: *const LogSite) !void {
const allocator = self.registryArena.allocator();
try self.enumTablesByPtr.ensureUnusedCapacity(allocator, @intCast(site.decoder.ops.len));
try self.enumTables.ensureUnusedCapacity(allocator, @intCast(site.decoder.ops.len));
for (site.decoder.ops) |op| {
if (op.enum_ref) |eref| {
if (!self.enumTablesByPtr.contains(eref)) {
std.debug.print("0x{x}\n", .{@intFromPtr(eref)});
self.enumTablesByPtr.putAssumeCapacity(eref, @intCast(self.enumTables.items.len));
self.enumTables.appendAssumeCapacity(eref);
}
}
}
}
/// Registers the event's logger and site, copies its payload into /// Registers the event's logger and site, copies its payload into
/// entriesArena and appends the entry. The caller still owns /// entriesArena and appends the entry. The caller still owns
/// `pending.serialized_args`. /// `pending.serialized_args`.
@ -415,6 +436,9 @@ pub const LogMem = struct {
.loggerId = loggerId, .loggerId = loggerId,
.siteId = siteId, .siteId = siteId,
}); });
try self.checkLogSiteForEnums(pending.site);
return &self.entries.items[self.entries.items.len - 1]; return &self.entries.items[self.entries.items.len - 1];
} }
}; };
@ -1075,7 +1099,7 @@ test "testing" {
defer deinit(); defer deinit();
const Logger = DeclareLogger("mylogger", .{ .verbosity = .verbose }); const Logger = DeclareLogger("mylogger", .{ .verbosity = .verbose });
Logger.addLog(@src(), .log, "{} {} who doesn't {} {s} 2 + 2 is {d}", .{ TestEnum.ending, TestEnum2.ending, true, "dragons", 4 }); Logger.addLog(@src(), .log, "{} {} who doesn't {} {s} 2 + 2 is {d}", .{ TestEnum.hello, TestEnum2.ending, true, "dragons", 4 });
Logger.addLog(@src(), .warn, "{} {} who doesn't {} {s} 2 + 2 is {d}", .{ TestEnum.ending, TestEnum2.ending, true, "dragons", 4 }); Logger.addLog(@src(), .warn, "{} {} who doesn't {} {s} 2 + 2 is {d}", .{ TestEnum.ending, TestEnum2.ending, true, "dragons", 4 });
Logger.addLog(@src(), .err, "{} {} who doesn't {} {s} 2 + 2 is {d}", .{ TestEnum.ending, TestEnum2.ending, true, "dragons", 4 }); Logger.addLog(@src(), .err, "{} {} who doesn't {} {s} 2 + 2 is {d}", .{ TestEnum.ending, TestEnum2.ending, true, "dragons", 4 });
@ -1130,14 +1154,23 @@ test "testing" {
try std.testing.expectEqualStrings(expected.written(), actual.written()); try std.testing.expectEqualStrings(expected.written(), actual.written());
} }
} }
const io = std.testing.io;
const cwd = std.Io.Dir.cwd();
try cwd.createDirPath(io, "zig-out/logs/");
const tdir = try cwd.openDir(io, "zig-out", .{});
{
const loggerFile = try sluggerformat.SlugOutputFile.create(
std.testing.allocator,
std.testing.io,
&gLoggerSystem.mem,
.{ .basedir = tdir, .logFilename = "test2.slg", .compressed = false },
);
try loggerFile.commit();
defer loggerFile.destroy();
}
{ {
const io = std.testing.io;
const cwd = std.Io.Dir.cwd();
try cwd.createDirPath(io, "zig-out/");
const tdir = try cwd.openDir(io, "zig-out", .{});
const file = try tdir.createFile(io, "output.bin", .{}); const file = try tdir.createFile(io, "output.bin", .{});
defer file.close(io); defer file.close(io);
@ -1151,11 +1184,13 @@ test "testing" {
std.debug.print("entry: {}", .{gLoggerSystem.mem.entries.items[0]}); std.debug.print("entry: {}", .{gLoggerSystem.mem.entries.items[0]});
for (0..12000) |_| { for (0..120) |_| {
try sluggerformat.write(std.testing.allocator, &gLoggerSystem.mem, &compressedWriter.writer); try sluggerformat.write(std.testing.allocator, &gLoggerSystem.mem, &compressedWriter.writer);
try compressedWriter.writer.flush(); try compressedWriter.writer.flush();
try w.flush(); try w.flush();
} }
try compressedWriter.finish();
} }
} }

View File

@ -1,12 +1,298 @@
// Binary LogMem format. Integers are little endian, strings are a u32 length followed by their bytes // Binary LogMem format. Integers are little endian, strings are a u32 length followed by their bytes
pub const version: u32 = 1; pub const version: u32 = 1;
const magic = "SLUG"; const magic: []const u8 = &.{ 0x1f, 'S', 'L', 'G' };
const compressedMagic: []const u8 = &.{ 0x1e, 'S', 'L', 'G' };
const frameMagic: []const u8 = &.{ 0x1f, 'S', 'F' };
const none = std.math.maxInt(u32); const none = std.math.maxInt(u32);
pub const WriteError = std.Io.Writer.Error || std.mem.Allocator.Error || error{TooLarge}; pub const WriteError = std.Io.Writer.Error || std.mem.Allocator.Error || error{TooLarge};
pub const ReadError = std.Io.Reader.Error || std.mem.Allocator.Error || error{ InvalidFile, UnsupportedVersion }; pub const ReadError = std.Io.Reader.Error || std.mem.Allocator.Error || error{ InvalidFile, UnsupportedVersion };
// wraps a writer and takes logmem, then outputs directly to the writer
// with propery flushing as an lz4'd stream
pub const SlugOutputFileOptions = struct {
basedir: ?std.Io.Dir = null, // null goes to cwd()
logFilename: []const u8 = "session_log.slg", // subpaths not allowed here
entriesFile: ?[]const u8 = null, // default: session_log.0.sle sle files contain the individual entries for the slg file format
// slg + slh files can be easily combined together into a .zip file for easy grouping
// may want to make these buffer sizes a lot bigger in the future.
entriesFileBufferSize: u32 = 1024 * 4,
headersFileBufferSize: u32 = 1024 * 4,
compressed: bool = true,
compressorSize: u32 = 1024 * 64,
};
pub const SlugOutputFile = struct {
out: SlugOutput,
opts: SlugOutputFileOptions,
entriesFile: std.Io.File,
headersFile: std.Io.File,
entriesFileWriter: std.Io.File.Writer,
headersFileWriter: std.Io.File.Writer,
entriesFileBuffer: []u8,
headersFileBuffer: []u8,
// working compression buffers for the two lz4 writers needed by SlugOutput
eBuffer: []u8,
hBuffer: []u8,
chunk: u32 = 0,
arena: std.heap.ArenaAllocator,
allocator: std.mem.Allocator,
io: std.Io,
pub fn validateFileName(name: []const u8) bool {
// zig fmt: off
return name.len > 4
and std.mem.eql(u8, name[name.len - 4 .. name.len], ".slg")
and std.mem.findAny(u8, name, "/\\") == null;
// zig fmt: on
}
pub fn commit(self: *@This()) !void {
try self.out.commit();
try self.entriesFileWriter.flush();
try self.headersFileWriter.flush();
}
pub fn create(allocator: std.mem.Allocator, io: std.Io, mem: *const LogMem, opts: SlugOutputFileOptions) !*@This() {
const new = try allocator.create(SlugOutputFile);
new.allocator = allocator;
new.arena = std.heap.ArenaAllocator.init(allocator);
new.chunk = 0;
new.opts = opts;
new.io = io;
const gpa = new.arena.allocator();
new.entriesFileBuffer = try gpa.alloc(u8, opts.entriesFileBufferSize);
errdefer gpa.free(new.entriesFileBuffer);
new.headersFileBuffer = try gpa.alloc(u8, opts.headersFileBufferSize);
errdefer gpa.free(new.headersFileBuffer);
new.hBuffer = try gpa.alloc(u8, opts.compressorSize);
errdefer gpa.free(new.hBuffer);
new.eBuffer = try gpa.alloc(u8, opts.compressorSize);
errdefer gpa.free(new.eBuffer);
if (!validateFileName(opts.logFilename)) {
std.debug.print("bad file name {s}\n", .{opts.logFilename});
return error.SlugFileBadExtension;
}
if (new.opts.entriesFile == null) {
const x = new.opts.logFilename;
new.opts.entriesFile = try std.fmt.allocPrint(gpa, "{s}.{d}.sle", .{ x[0 .. x.len - 4], new.chunk });
}
if (new.opts.basedir == null) {
new.opts.basedir = std.Io.Dir.cwd();
}
new.headersFile = try new.opts.basedir.?.createFile(io, new.opts.logFilename, .{});
errdefer new.headersFile.close(io);
new.entriesFile = try new.opts.basedir.?.createFile(io, new.opts.entriesFile.?, .{});
new.entriesFileWriter = new.entriesFile.writer(io, new.entriesFileBuffer);
new.headersFileWriter = new.headersFile.writer(io, new.headersFileBuffer);
try new.out.init(
mem,
gpa,
io,
&new.entriesFileWriter.interface,
&new.headersFileWriter.interface,
new.eBuffer,
new.hBuffer,
opts.compressed,
);
return new;
}
pub fn flushAll(self: @This()) void {
self.logOutput.flush();
self.entriesFileWriter.flush() catch {};
self.headersFileWriter.flush() catch {};
self.entriesFile.close(self.io);
self.headersFile.close(self.io);
}
pub fn destroy(self: *@This()) void {
self.arena.deinit();
self.allocator.destroy(self);
}
};
// log output helper, wraps writers and gives the caller state access to the state of the write-out
const SlugOutput = struct {
// --- logger header facility ---
logSitesWritten: usize,
loggersWritten: usize,
enumTablesWritten: usize,
entriesWritten: usize,
entriesGeneration: u32 = 0,
sessionWritten: bool = false,
// --- end of logger header facility ---
allocator: std.mem.Allocator,
io: std.Io,
mem: *const LogMem,
workBuffer: std.ArrayList(u8), // Header frame buffer, first 4 bytes is the size of the entire buffer
entriesW: *std.Io.Writer,
headersW: *std.Io.Writer,
eLZ4: ?Lz4Writer = null,
hLZ4: ?Lz4Writer = null,
pub fn init(
self: *@This(),
mem: *const LogMem,
allocator: std.mem.Allocator,
io: std.Io,
entriesWriter: *std.Io.Writer,
headerWriter: *std.Io.Writer,
eBuffer: ?[]u8,
hBuffer: ?[]u8,
compression: bool,
) !void {
self.* = .{
.io = io,
.workBuffer = .empty,
.logSitesWritten = 0,
.loggersWritten = 0,
.entriesWritten = 0,
.enumTablesWritten = 0,
.entriesGeneration = 0,
.allocator = allocator,
.mem = mem,
.entriesW = entriesWriter,
.headersW = headerWriter,
};
if (compression == true) {
self.eLZ4 = try Lz4Writer.init(allocator, entriesWriter, .{ .buffer = eBuffer.? });
self.hLZ4 = try Lz4Writer.init(allocator, headerWriter, .{ .buffer = hBuffer.? });
self.entriesW = &self.eLZ4.?.writer;
self.headersW = &self.hLZ4.?.writer;
}
}
// write the one-time-only session metadata to the slg file
pub fn writeSessionHeader(self: *@This()) !void {
var frame = std.Io.Writer.Allocating.fromArrayList(self.allocator, &self.workBuffer);
defer {
self.workBuffer = frame.toArrayList();
}
self.sessionWritten = true;
const w = &frame.writer;
_ = try w.write(if (self.eLZ4 != null) compressedMagic else magic);
// header format =
// 0x0: 0x1f SLH
// 0x4: headerSize i32 includes header;
try w.writeInt(i32, -1, .little); // write -1 for now
const headerSizeOffset: usize = 4;
// 96 bits... utc time
try w.writeInt(i96, self.mem.start_utc_time.raw.nanoseconds, .little);
const written = frame.written();
std.mem.writeInt(
i32,
written[headerSizeOffset .. headerSizeOffset + 4],
@as(i32, @intCast(written.len)),
.little,
);
try self.headersW.writeAll(written);
}
pub const KindTag = enum(u8) {
enumTable = 0x50,
logSite = 0x51,
loggerDef = 0x52,
};
fn writeEnumTable(self: *@This(), writer: *std.Io.Writer, entry: *const EnumTable) !void {
// preceeded by the command byte + definition command length
try writer.writeInt(u8, @backingInt(KindTag.enumTable), .little);
try writer.writeInt(u32, @intCast(entry.len), .little);
for (entry.*) |e| {
try writer.writeInt(i64, e.value, .little);
try writer.writeInt(u32, @intCast(e.name.len), .little);
try writer.writeAll(e.name);
}
self.enumTablesWritten += 1;
}
pub fn commitHeaderChanges(self: *@This()) !void {
// 1. create a temporary buffer for this current frame.
self.workBuffer.clearRetainingCapacity();
var frame = std.Io.Writer.Allocating.fromArrayList(self.allocator, &self.workBuffer);
const fWriter = &frame.writer;
try fWriter.writeAll(frameMagic);
const frameSizeOffset = frame.written().len;
try fWriter.writeInt(i32, -1, .little); // -1 indicates this frame did not successfully write
std.debug.print("entries {d}\n", .{self.mem.enumTables.items.len});
// 1. write the changes to header file first if there are new entries in the registry
for (self.mem.enumTables.items[self.enumTablesWritten..self.mem.enumTables.items.len]) |entry| {
// write each entry
try self.writeEnumTable(fWriter, entry);
}
// 2. write out the entries to the .sle file
const written = frame.written();
std.mem.writeInt(i32, written[frameSizeOffset..][0..4], @intCast(written.len), .little);
try self.headersW.writeAll(written);
try self.headersW.flush();
}
pub fn commit(self: *@This()) !void {
// write out all unwritten sites, loggers, tables, and entries
if (self.isCurrent()) return;
if (!self.sessionWritten) {
try self.writeSessionHeader();
}
try self.commitHeaderChanges();
}
pub fn isCurrent(self: *@This()) bool {
const mem = self.mem;
// zig fmt: off
return self.entriesGeneration == mem.entriesGeneration
and self.logSitesWritten == mem.logSites.items.len
and self.loggersWritten == mem.loggers.items.len
and self.enumTablesWritten == mem.enumTables.items.len;
// zig fmt: on
}
};
pub fn testWrite(scratch: std.mem.Allocator, mem: *const LogMem, writer: *std.Io.Writer) WriteError!void {
_ = scratch;
try writer.writeAll(magic);
try writer.writeInt(u8, version, .little);
try writer.writeInt(i96, mem.start_utc_time.raw.nanoseconds, .little);
}
/// Writes the registries and entries of `mem`. `scratch` holds the enum table /// Writes the registries and entries of `mem`. `scratch` holds the enum table
/// index while writing and is freed before returning. /// index while writing and is freed before returning.
pub fn write(scratch: std.mem.Allocator, mem: *const LogMem, writer: *std.Io.Writer) WriteError!void { pub fn write(scratch: std.mem.Allocator, mem: *const LogMem, writer: *std.Io.Writer) WriteError!void {
@ -293,3 +579,4 @@ const ArgsDecoderOp = slugger.ArgsDecoderOp;
const ArgsDecoderOpKind = slugger.ArgsDecoderOpKind; const ArgsDecoderOpKind = slugger.ArgsDecoderOpKind;
const RenderOp = slugger.RenderOp; const RenderOp = slugger.RenderOp;
const lz4 = @import("lz4"); const lz4 = @import("lz4");
const Lz4Writer = lz4.Lz4Writer;