working on serializer format now

This commit is contained in:
Peterino2 2026-10-24 13:32:04 -07:00
parent 15430ca28c
commit 1a07a5388c
9 changed files with 124 additions and 47 deletions

View File

@ -1,3 +1,3 @@
# Ribtech # Riblab
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

@ -57,12 +57,12 @@ pub const Options = struct {
box3d_validate: ?bool = null, box3d_validate: ?bool = null,
}; };
// standard set of options that all RibTech modules and dependenices shall use. // standard set of options that all riblab modules and dependenices shall use.
pub fn declareOptions(b: *std.Build) Options { pub fn declareOptions(b: *std.Build) Options {
return .{ return .{
.target = b.standardTargetOptions(.{}), .target = b.standardTargetOptions(.{}),
.optimize = b.standardOptimizeOption(.{}), .optimize = b.standardOptimizeOption(.{}),
.monolithic = b.option(bool, "monolithic", "builds RibTech dependencies for static linking") orelse false, .monolithic = b.option(bool, "monolithic", "builds RibLab dependencies for static linking") orelse false,
.tracy = b.option(bool, "tracy", "builds with tracy support") orelse false, .tracy = b.option(bool, "tracy", "builds with tracy support") orelse false,
.renderer = b.option([]const u8, "renderer", "renderer backend: sgpu_main, gl_low_spec, headless") orelse "sgpu_main", .renderer = b.option([]const u8, "renderer", "renderer backend: sgpu_main, gl_low_spec, headless") orelse "sgpu_main",
.box3d_validate = b.option(bool, "box3d-validate", "enable heavy Box3D validation"), .box3d_validate = b.option(bool, "box3d-validate", "enable heavy Box3D validation"),
@ -129,7 +129,7 @@ pub fn isEngineDependency(name: []const u8) bool {
pub fn build(b: *std.Build) void { pub fn build(b: *std.Build) void {
const target = b.standardTargetOptions(.{}); const target = b.standardTargetOptions(.{});
const optimize = b.standardOptimizeOption(.{}); const optimize = b.standardOptimizeOption(.{});
const monolithic = b.option(bool, "monolithic", "builds RibTech dependencies for static linking") orelse false; const monolithic = b.option(bool, "monolithic", "builds RibLab dependencies for static linking") orelse false;
const r = MakeModlib(b, .{ const r = MakeModlib(b, .{
.name = "bh", .name = "bh",

View File

@ -186,7 +186,7 @@ test "multi-sparse-basic" {
std.debug.print("handle2: {any}\n", .{testSet.get(sparseHandle2, .field1).?.*}); std.debug.print("handle2: {any}\n", .{testSet.get(sparseHandle2, .field1).?.*});
} }
// As RibTech is primarily a playground for me to learn and practice programming, // As RibLab is primarily a playground for me to learn and practice programming,
// There will be some implementations of basic data structures. For fun ofc // There will be some implementations of basic data structures. For fun ofc
pub fn AppendToArrayListUnique(list: anytype, value: anytype) !void { pub fn AppendToArrayListUnique(list: anytype, value: anytype) !void {
for (list.items) |v| { for (list.items) |v| {
@ -374,17 +374,16 @@ test "managed ring queue uses stored io mutex" {
} }
test "spin child process echo" { test "spin child process echo" {
const io = std.testing.io;
{ {
std.debug.print("spin child process\n", .{}); std.debug.print("spin child process\n", .{});
const process = try shell.ShellProcess.init(std.testing.allocator, io, &.{ "echo", "lmao 2 nova" }); const process = try shell.ShellProcess.init(std.testing.allocator, &.{ "echo", "lmao 2 nova" });
defer process.deinit(); defer process.deinit();
std.debug.print("child process created: {any}\n", .{process.argv}); std.debug.print("child process created: {any}\n", .{process.argv});
} }
{ {
std.debug.print("spin child process 2\n", .{}); std.debug.print("spin child process 2\n", .{});
const process = try shell.ShellProcess.initCmd(std.testing.allocator, io, "echo lmao2nova -target='lmao 3 nova'"); const process = try shell.ShellProcess.initCmd(std.testing.allocator, "echo lmao2nova -target='lmao 3 nova'");
defer process.deinit(); defer process.deinit();
std.debug.print("{any}\n", .{process.argv}); std.debug.print("{any}\n", .{process.argv});
} }

View File

@ -1,7 +1,8 @@
const std = @import("std"); const std = @import("std");
const stats = @import("stats.zig"); const stats = @import("stats.zig");
// fast bump-only allocator, not threadsafe. see BumpArenaThreaded for the mutex based version. // fast bump-only allocator with checkpoints, not threadsafe. for a threadsafe arena
// use std.heap.ArenaAllocator.
// //
// memory comes from a linked list of blocks taken from the backing allocator. // memory comes from a linked list of blocks taken from the backing allocator.
// blocks are never returned to the backing allocator until reset(.free_all) or // blocks are never returned to the backing allocator until reset(.free_all) or
@ -256,6 +257,7 @@ pub const BumpCheckpoint = struct {
// mutex based, threadsafe BumpArenaAdvanced. does not support checkpoints, // mutex based, threadsafe BumpArenaAdvanced. does not support checkpoints,
// rewinding would release other threads' allocations. // rewinding would release other threads' allocations.
/// Deprecated: use std.heap.ArenaAllocator, its allocator is lock-free and threadsafe.
pub const BumpArenaThreaded = struct { pub const BumpArenaThreaded = struct {
arena: BumpArenaAdvanced, arena: BumpArenaAdvanced,
io_context: std.Io, io_context: std.Io,
@ -321,12 +323,12 @@ pub const BumpArenaThreaded = struct {
}; };
test "bump-it-uppp" { test "bump-it-uppp" {
var arena = BumpArenaThreaded.init(std.testing.allocator, std.testing.io); var arena = BumpArenaAdvanced.init(std.testing.allocator);
defer arena.deinit(); defer arena.deinit();
} }
test "reset clears usage" { test "reset clears usage" {
var arena = BumpArenaThreaded.init(std.testing.allocator, std.testing.io); var arena = BumpArenaAdvanced.init(std.testing.allocator);
defer arena.deinit(); defer arena.deinit();
const allocator = arena.allocator(); const allocator = arena.allocator();

View File

@ -648,7 +648,7 @@ test "concatSlice" {
const joined = try left.concatSlice("tech"); const joined = try left.concatSlice("tech");
defer joined.drop(); defer joined.drop();
try std.testing.expectEqualStrings("ribtech", joined.getUtf8()); try std.testing.expectEqualStrings("riblab", joined.getUtf8());
try std.testing.expectEqualStrings("rib", left.getUtf8()); try std.testing.expectEqualStrings("rib", left.getUtf8());
} }

View File

@ -6,14 +6,14 @@ pub const ShellProcess = struct {
argv: []const []const u8 = undefined, argv: []const []const u8 = undefined,
ownedArgs: ?[][]u8 = null, ownedArgs: ?[][]u8 = null,
stringArena: p2.BumpArenaThreaded = undefined, stringArena: std.heap.ArenaAllocator = undefined,
// initialize the shellprocess from a windows cmd string // initialize the shellprocess from a windows cmd string
pub fn initCmd(alloc: std.mem.Allocator, io: std.Io, cmd: []const u8) !*@This() { pub fn initCmd(alloc: std.mem.Allocator, cmd: []const u8) !*@This() {
const self = try alloc.create(@This()); const self = try alloc.create(@This());
self.* = .{ self.* = .{
.backingAllocator = alloc, .backingAllocator = alloc,
.stringArena = p2.BumpArenaThreaded.init(alloc, io), .stringArena = .init(alloc),
}; };
try self.splitArgsFromCmd(cmd); try self.splitArgsFromCmd(cmd);
@ -21,11 +21,11 @@ pub const ShellProcess = struct {
return self; return self;
} }
pub fn init(alloc: std.mem.Allocator, io: std.Io, argv: []const []const u8) !*@This() { pub fn init(alloc: std.mem.Allocator, argv: []const []const u8) !*@This() {
const self = try alloc.create(@This()); const self = try alloc.create(@This());
self.* = .{ self.* = .{
.backingAllocator = alloc, .backingAllocator = alloc,
.stringArena = p2.BumpArenaThreaded.init(alloc, io), .stringArena = .init(alloc),
}; };
try self.setArgsOwned(argv); try self.setArgsOwned(argv);

View File

@ -351,17 +351,16 @@ pub const LogMem = struct {
start_utc_time: std.Io.Clock.Timestamp = undefined, start_utc_time: std.Io.Clock.Timestamp = undefined,
// Consumer-owned registries; producers only reference static descriptors. // Consumer-owned registries; producers only reference static descriptors.
logMap: std.AutoHashMapUnmanaged(*const LogSite, u32) = .empty, logSitesByPtr: std.AutoHashMapUnmanaged(*const LogSite, u32) = .empty,
loggerStates: std.AutoHashMapUnmanaged(*const LoggerState, u32) = .empty, logSites: std.ArrayList(*const LogSite) = .empty,
loggerStatesById: std.ArrayList(*const LoggerState) = .empty,
logSites: std.ArrayList(LogSite) = .empty,
loggersByPtr: std.AutoHashMapUnmanaged(*const LoggerState, u32) = .empty,
loggers: std.ArrayList(*const LoggerState) = .empty,
// Entries and their payloads are owned by whoever filled them, e.g. the
// logger system's flush arena or a LogMemFile's arena.
entries: std.ArrayList(StructuredLog) = .empty, entries: std.ArrayList(StructuredLog) = .empty,
pub fn deinit(self: *@This(), payload_allocator: std.mem.Allocator) void {
for (self.entries.items) |entry| payload_allocator.free(entry.serialized_args);
}
pub fn init(self: *@This(), io: std.Io) void { pub fn init(self: *@This(), io: std.Io) void {
self.start_time = .now(io, .awake); self.start_time = .now(io, .awake);
self.start_utc_time = .now(io, .real); self.start_utc_time = .now(io, .real);
@ -381,26 +380,30 @@ pub const LogMem = struct {
} }
fn getOrRegisterSite(self: *@This(), allocator: std.mem.Allocator, site: *const LogSite) !u32 { fn getOrRegisterSite(self: *@This(), allocator: std.mem.Allocator, site: *const LogSite) !u32 {
if (self.logMap.get(site)) |id| return id; if (self.loggerSitesBy.get(site)) |id| return id;
try self.logMap.ensureUnusedCapacity(allocator, 1); try self.logSitesByPtr.ensureUnusedCapacity(allocator, 1);
try self.logSites.ensureUnusedCapacity(allocator, 1); try self.logSites.ensureUnusedCapacity(allocator, 1);
const id = std.math.cast(u32, self.logSites.items.len) orelse return error.TooManySites; const id = std.math.cast(u32, self.logSites.items.len) orelse return error.TooManySites;
// Site metadata is static; hot-reloaded modules remain loaded. // Site metadata is static; hot-reloaded modules remain loaded.
self.logSites.appendAssumeCapacity(site.*); self.logSites.appendAssumeCapacity(site);
self.logMap.putAssumeCapacity(site, id); self.logSitesByPtr.putAssumeCapacity(site, id);
return id; return id;
} }
fn accept(self: *@This(), allocator: std.mem.Allocator, pending: PendingLog) !StructuredLog { /// Registers the event's logger and site in `registry` and copies its payload
/// into `payloads`. The caller still owns `pending.serialized_args`.
fn accept(self: *@This(), registry: std.mem.Allocator, payloads: std.mem.Allocator, pending: PendingLog) !StructuredLog {
const loggerId = try self.getOrRegisterLoggerState(registry, pending.logger);
const sourceId = try self.getOrRegisterSite(registry, pending.site);
return .{ return .{
.serialized_args = pending.serialized_args, .serialized_args = try payloads.dupe(u8, pending.serialized_args),
.verbosity = pending.verbosity, .verbosity = pending.verbosity,
.usSinceStart = pending.usSinceStart, .usSinceStart = pending.usSinceStart,
.loggerId = try self.getOrRegisterLoggerState(allocator, pending.logger), .loggerId = loggerId,
.sourceId = try self.getOrRegisterSite(allocator, pending.site), .sourceId = sourceId,
}; };
} }
}; };
@ -414,7 +417,10 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
stdout_file_writer: std.Io.File.Writer = undefined, stdout_file_writer: std.Io.File.Writer = undefined,
stdout_writer: *std.Io.Writer = undefined, stdout_writer: *std.Io.Writer = undefined,
io: std.Io = undefined, io: std.Io = undefined,
// Registries and writers; lives until deinit.
arena: std.heap.ArenaAllocator = undefined, arena: std.heap.ArenaAllocator = undefined,
// Drained entries and their payloads; dropped all at once by resetFlushArena.
flushArena: std.heap.ArenaAllocator = undefined,
backing: std.mem.Allocator = undefined, backing: std.mem.Allocator = undefined,
payload_allocator: std.mem.Allocator = undefined, payload_allocator: std.mem.Allocator = undefined,
queue_buffer: []PendingLog = undefined, queue_buffer: []PendingLog = undefined,
@ -496,7 +502,7 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
var count: usize = 0; var count: usize = 0;
while (count < self.queue_buffer.len) : (count += 1) { while (count < self.queue_buffer.len) : (count += 1) {
try self.mem.entries.ensureUnusedCapacity(self.arena.allocator(), 1); try self.mem.entries.ensureUnusedCapacity(self.flushArena.allocator(), 1);
var pending: [1]PendingLog = undefined; var pending: [1]PendingLog = undefined;
const n = self.queue.getUncancelable(self.io, &pending, 0) catch |err| switch (err) { const n = self.queue.getUncancelable(self.io, &pending, 0) catch |err| switch (err) {
error.Closed => break, error.Closed => break,
@ -505,9 +511,10 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
if (n == 0) break; if (n == 0) break;
const entry = pending[0]; const entry = pending[0];
// If registration fails, this dequeued payload must still be freed. // The payload is copied into the flush arena, so the producer's
const log = self.mem.accept(self.arena.allocator(), entry) catch |err| { // copy is freed whether or not accept succeeds.
self.payload_allocator.free(entry.serialized_args); defer self.payload_allocator.free(entry.serialized_args);
const log = self.mem.accept(self.arena.allocator(), self.flushArena.allocator(), entry) catch |err| {
_ = self.dropped.fetchAdd(1, .monotonic); _ = self.dropped.fetchAdd(1, .monotonic);
return err; return err;
}; };
@ -528,6 +535,15 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
return count; return count;
} }
/// Drops every drained entry and its payload, starting a new generation.
/// Write entries out first if they should be kept. Invalidates every
/// StructuredLog drained so far; registries are kept.
pub fn resetFlushArena(self: *@This()) void {
self.mem.entries = .empty;
_ = self.flushArena.reset(.retain_capacity);
self.stats.bytesUsed = 0;
}
/// Stop accepting events. Already queued events can still be drained. /// Stop accepting events. Already queued events can still be drained.
pub fn close(self: *@This()) void { pub fn close(self: *@This()) void {
self.queue.close(self.io); self.queue.close(self.io);
@ -541,7 +557,8 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
@panic("Check failed"); @panic("Check failed");
} }
/// Producer allocations must be thread-safe, independently of the consumer arena. /// `payload_allocator` must be thread-safe and free in any order: producers
/// allocate payloads, the consumer frees each one as soon as it is drained.
pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator, payload_allocator: std.mem.Allocator) void { pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator, payload_allocator: std.mem.Allocator) void {
check(options.queue_capacity >= 64, "queue capacity abnormally small {d}", .{options.queue_capacity}); check(options.queue_capacity >= 64, "queue capacity abnormally small {d}", .{options.queue_capacity});
check(options.queue_capacity <= 10000, "queue capacity abnormally large {d}", .{options.queue_capacity}); check(options.queue_capacity <= 10000, "queue capacity abnormally large {d}", .{options.queue_capacity});
@ -552,6 +569,7 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
self.backing = allocator; self.backing = allocator;
self.payload_allocator = payload_allocator; self.payload_allocator = payload_allocator;
self.arena = std.heap.ArenaAllocator.init(allocator); self.arena = std.heap.ArenaAllocator.init(allocator);
self.flushArena = std.heap.ArenaAllocator.init(allocator);
self.queue_buffer = allocator.alloc(PendingLog, options.queue_capacity) catch { self.queue_buffer = allocator.alloc(PendingLog, options.queue_capacity) catch {
std.debug.print("queue_buffer_alloc failed {d}", .{options.queue_capacity}); std.debug.print("queue_buffer_alloc failed {d}", .{options.queue_capacity});
@panic("Check failed"); @panic("Check failed");
@ -562,7 +580,7 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
self.mem.init(io); self.mem.init(io);
} }
/// Producers must have finished. Frees both drained and undrained payloads. /// Producers must have finished. Frees undrained payloads and the flush arena.
pub fn deinit(self: *@This()) void { pub fn deinit(self: *@This()) void {
self.close(); self.close();
var pending: [16]PendingLog = undefined; var pending: [16]PendingLog = undefined;
@ -571,8 +589,8 @@ pub fn DeclareLoggerSystem(comptime opts: LoggerSystemInitOptions) type {
if (n == 0) break; if (n == 0) break;
for (pending[0..n]) |entry| self.payload_allocator.free(entry.serialized_args); for (pending[0..n]) |entry| self.payload_allocator.free(entry.serialized_args);
} }
self.mem.deinit(self.payload_allocator);
self.backing.free(self.queue_buffer); self.backing.free(self.queue_buffer);
self.flushArena.deinit();
self.arena.deinit(); self.arena.deinit();
} }
}; };
@ -644,7 +662,6 @@ pub const LogRef = struct {
pub const LoggerState = struct { pub const LoggerState = struct {
name: []const u8, name: []const u8,
verbosity: std.atomic.Value(Verbosity), verbosity: std.atomic.Value(Verbosity),
stdout: bool = false, // mirrors it's output to stdout
}; };
pub const LoggerOptions = struct { pub const LoggerOptions = struct {
@ -992,7 +1009,6 @@ pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptio
pub var loggerState: LoggerState = .{ pub var loggerState: LoggerState = .{
.name = LoggerName, .name = LoggerName,
.verbosity = .init(opts.verbosity), .verbosity = .init(opts.verbosity),
.stdout = opts.has_stdout,
}; };
pub fn setVerbosity(v: Verbosity) void { pub fn setVerbosity(v: Verbosity) void {
@ -1217,9 +1233,13 @@ test "testing" {
defer y.deinit(std.testing.allocator); defer y.deinit(std.testing.allocator);
std.debug.print("log>\n{s}\nlength={d}\nbytesUsed={d}\n", .{ y.items, y.items.len, gLoggerSystem.stats.bytesUsed }); std.debug.print("log>\n{s}\nlength={d}\nbytesUsed={d}\n", .{ y.items, y.items.len, gLoggerSystem.stats.bytesUsed });
var serializer: sluggerformat.LogMemSerializer = undefined; // testing serializer
try serializer.init(std.testing.io, std.testing.allocator, &gLoggerSystem.mem, .write); {
defer serializer.deinit(); var serializer: sluggerformat.LogMemSerializer = undefined;
try serializer.init(std.testing.io, std.testing.allocator, &gLoggerSystem.mem, .write);
defer serializer.deinit();
try serializer.populateForWrite();
}
} }
pub const sluggerformat = @import("sluggerformat.zig"); pub const sluggerformat = @import("sluggerformat.zig");

View File

@ -60,6 +60,12 @@ pub const LogMemSerializer = struct {
logSitesByPtr: std.AutoHashMapUnmanaged(*LogSite, u32) = .empty, logSitesByPtr: std.AutoHashMapUnmanaged(*LogSite, u32) = .empty,
logSites: std.ArrayList(*LogSite) = .empty, logSites: std.ArrayList(*LogSite) = .empty,
loggersByPtr: std.AutoHashMapUnmanaged(*LoggerState, u32) = .empty,
loggers: std.ArrayList(*LoggerState) = .empty,
enumListByPtr: std.ArrayList(*EnumEntry, u32) = .empty,
enumList: std.ArrayList(EnumEntry) = .empty,
io: std.Io, io: std.Io,
pub const Mode = enum { pub const Mode = enum {
@ -77,16 +83,65 @@ pub const LogMemSerializer = struct {
}; };
} }
pub fn addOrRegisterLogSite(self: *@This(), logSite: *LogSite) !u32 { pub fn populateForWrite(self: *@This()) !void {
// will do this oppurtunistically later
for (self.mem.logSites.items) |logSite| {
_ = try self.addOrRegisterLogSite(logSite);
}
for (self.mem.loggerStatesById.items) |loggerState| {
_ = try self.addOrRegisterLogger(loggerState);
}
for (self.mem.)
}
pub fn addOrRegisterEnumEntry(self: *@This(), state: *const EnumEntry) !u32
{
}
pub fn addOrRegisterLogger(self: *@This(), state: *const LoggerState) !u32 {
if (self.mode == .read)
return error.ReadOnlySerializer;
try self.logSitesByPtr.ensureUnusedCapacity(self.backing, 1);
try self..ensureUnusedCapacity(self.backing, 1);
const allocator = self.arena.allocator();
const newState = try allocator.create(LoggerState);
newState.* = .{
.verbosity = state.verbosity.load(.monotonic),
.name = try allocator.dupe(u8, state.name),
};
const id: u32 = @intCast(self.loggers.items.len);
self.loggersByPtr.putAssumeCapacity(self.backing, state, id);
self.loggers.appendAssumeCapacity(self.backing, state, id);
return id;
}
pub fn addOrRegisterLogSite(self: *@This(), logSite: *const LogSite) !u32 {
if (self.mode == .read) if (self.mode == .read)
return error.ReadOnlySerializer; return error.ReadOnlySerializer;
const allocator = self.arena.allocator(); const allocator = self.arena.allocator();
const newSite = try allocator.create(LogSite); const newSite = try allocator.create(LogSite);
try deepCopyLogSite(allocator, logSite, newSite); try deepCopyLogSite(allocator, logSite, newSite);
const id: u32 = @intCast(self.logSites.items.len);
self.logSitesByPtr.putAssumeCapacity(self.backing, newSite, id);
self.logSites.appendAssumeCapacity(self.backing, newSite);
return id;
} }
pub fn deinit(self: *@This()) void { pub fn deinit(self: *@This()) void {
self.logSites.deinit(self.backing);
self.logSitesByPtr.deinit(self.backing);
self.loggers.deinit(self.backing);
self.loggersByPtr.deinit(self.backing);
self.arena.deinit(); self.arena.deinit();
} }
}; };
@ -100,6 +155,7 @@ const EnumTable = slugger.EnumTable;
const EnumEntry = slugger.EnumEntry; const EnumEntry = slugger.EnumEntry;
const ArgsDecoderOp = slugger.ArgsDecoderOp; const ArgsDecoderOp = slugger.ArgsDecoderOp;
const RenderOp = slugger.RenderOp; const RenderOp = slugger.RenderOp;
const LoggerSystem = slugger.LoggerSystem;
const LogMem = slugger.LogMem; const LogMem = slugger.LogMem;
const p2 = @import("p2"); const p2 = @import("p2");

View File

@ -1,4 +1,4 @@
// this thing eats a ribtech top level zig file and generates a C header // this thing eats a riblab top level zig file and generates a C header
pub fn main(init: std.process.Init) !void { pub fn main(init: std.process.Init) !void {
const args = init.minimal.args; const args = init.minimal.args;