diff --git a/engine/lib/p2/src/structures/structured-logging.zig b/engine/lib/p2/src/structures/structured-logging.zig index 5baa8af..b9abb8b 100644 --- a/engine/lib/p2/src/structures/structured-logging.zig +++ b/engine/lib/p2/src/structures/structured-logging.zig @@ -5,42 +5,42 @@ // or it can log to a second writer thread. // but the way it all works is it goes through this logger -const BumpArena = @import("bump-arena.zig"); - -pub const ArgsSerializerOpKind = enum { +pub const ArgsDecoderOpKind = enum { + boolean, integer, floating, string, // []u8 and []const u8 structure, }; -pub const ArgsSerializerOp = struct { - kind: ArgsSerializerOpKind, +pub const ArgsDecoderOp = struct { + kind: ArgsDecoderOpKind, bits: u16 = 0, signed: bool = false, fields: []const Field = &.{}, is_tuple: bool = false, - pub const Field = struct { name: []const u8, op: ArgsSerializerOp }; + pub const Field = struct { name: []const u8, op: ArgsDecoderOp }; }; -pub const ArgsSerializer = struct { - ops: []const ArgsSerializerOp, +pub const ArgsDecoder = struct { + ops: []const ArgsDecoderOp, /// Static metadata can be persisted as values; no encoder function pointers. - pub fn fromArgs(comptime Args: type) ArgsSerializer { + pub fn fromArgs(comptime Args: type) ArgsDecoder { const ops = comptime blk: { const types = @typeInfo(Args).@"struct".field_types; - var result: [types.len]ArgsSerializerOp = undefined; + var result: [types.len]ArgsDecoderOp = undefined; for (types, 0..) |T, i| result[i] = schemaFor(T); break :blk result; }; return .{ .ops = &ops }; } - fn schemaFor(comptime T: type) ArgsSerializerOp { - var op: ArgsSerializerOp = .{ .kind = kindFor(T) }; + fn schemaFor(comptime T: type) ArgsDecoderOp { + var op: ArgsDecoderOp = .{ .kind = ArgsSerializer.kindFor(T) }; switch (@typeInfo(T)) { + .bool => op.bits = 8, .comptime_int => op.bits = 32, .comptime_float => op.bits = 64, .int => |info| { @@ -50,7 +50,7 @@ pub const ArgsSerializer = struct { .float => |info| op.bits = info.bits, .@"struct" => |info| { const fields = comptime blk: { - var result: [info.field_names.len]ArgsSerializerOp.Field = undefined; + var result: [info.field_names.len]ArgsDecoderOp.Field = undefined; for (info.field_names, info.field_types, 0..) |name, F, i| { result[i] = .{ .name = name, .op = schemaFor(F) }; } @@ -63,32 +63,29 @@ pub const ArgsSerializer = struct { } return op; } +}; +pub const ArgsSerializer = struct { pub const Error = std.Io.Writer.Error || error{ - InvalidOperationCount, - InvalidOperation, IntegerOutOfRange, StringTooLong, }; /// Numbers use little endian. Comptime integers use u32 and comptime floats /// use f64. Typed numbers retain their width, rounded up to whole bytes. + /// Booleans use one byte: 0 for false, 1 for true. /// Strings have a u32 byte length followed by their contents. Struct fields /// are encoded recursively in declaration order, without padding or tags. /// The decoder must know the argument types and struct field schema. - pub fn serialize(self: @This(), args: anytype, output: *std.Io.Writer) Error!void { - if (self.ops.len != args.len) return error.InvalidOperationCount; - // Validate the entire op list before writing any arguments. - inline for (args, 0..) |a, i| { - if (self.ops[i].kind != kindFor(@TypeOf(a))) return error.InvalidOperation; - } + pub fn serialize(args: anytype, output: *std.Io.Writer) Error!void { inline for (args) |a| { try writeValue(a, output); } } - fn kindFor(comptime T: type) ArgsSerializerOpKind { + fn kindFor(comptime T: type) ArgsDecoderOpKind { return switch (@typeInfo(T)) { + .bool => .boolean, .comptime_int, .int => .integer, .comptime_float, .float => .floating, .@"struct" => .structure, @@ -109,6 +106,7 @@ pub const ArgsSerializer = struct { fn writeValue(value: anytype, output: *std.Io.Writer) Error!void { const T = @TypeOf(value); switch (comptime kindFor(T)) { + .boolean => try output.writeByte(@intFromBool(value)), .integer => { if (T == comptime_int) { return output.writeInt(u32, std.math.cast(u32, value) orelse return error.IntegerOutOfRange, .little); @@ -167,8 +165,9 @@ pub const RenderOp = union(enum) { @compileError("Unsupported structured log format: " ++ spec); } - fn supports(self: Format, kind: ArgsSerializerOpKind) bool { + fn supports(self: Format, kind: ArgsDecoderOpKind) bool { return switch (kind) { + .boolean => self == .any, .integer => switch (self) { .any, .decimal, .hex_lower, .hex_upper, .binary, .octal => true, else => false, @@ -186,7 +185,7 @@ pub const RenderOp = union(enum) { pub const LogSite = struct { source: LogRef, - serializer: ArgsSerializer, + decoder: ArgsDecoder, render_ops: []const RenderOp, pub fn init(comptime source: LogRef, comptime Args: type) LogSite { @@ -194,7 +193,7 @@ pub const LogSite = struct { ref.args_type = @typeName(Args); return .{ .source = ref, - .serializer = ArgsSerializer.fromArgs(Args), + .decoder = ArgsDecoder.fromArgs(Args), .render_ops = comptime buildRenderOps(source.fmt, Args), }; } @@ -264,173 +263,196 @@ pub const Verbosity = enum(u8) { err, }; -test "argsSerializer tests" { - const expectBytes = struct { - fn check(ops: []const ArgsSerializerOp, args: anytype, expected: []const u8) !void { - var writer = std.Io.Writer.Allocating.init(std.testing.allocator); - defer writer.deinit(); - try (ArgsSerializer{ .ops = ops }).serialize(args, &writer.writer); - try std.testing.expectEqualSlices(u8, expected, writer.written()); - } - }.check; +var gLoggerSystem: LoggerSystem = undefined; - // Existing comptime integer representation, including its upper boundary. - try expectBytes(&.{ - .{ .kind = .integer }, .{ .kind = .integer }, - .{ .kind = .integer }, .{ .kind = .integer }, - }, .{ 0, 2, 3, 0xffffffff }, &.{ - 0, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 255, 255, 255, 255, - }); - try expectBytes(&.{.{ .kind = .floating }}, .{1.5}, &.{ 0, 0, 0, 0, 0, 0, 0xf8, 0x3f }); +/// Producer allocations must be thread-safe, independently of the consumer arena. +pub const LoggerSystemInitOptions = struct { + queue_capacity: usize = 1024, + payload_allocator: std.mem.Allocator = std.heap.smp_allocator, +}; - // Runtime values, signed integers, and widths that need byte rounding. - var number: i16 = -2; - _ = &number; - try expectBytes(&.{ - .{ .kind = .integer }, .{ .kind = .integer }, .{ .kind = .integer }, - .{ .kind = .integer }, .{ .kind = .integer }, .{ .kind = .integer }, - }, .{ number, @as(u8, 255), @as(u32, 0x12345678), @as(u64, 0x0102030405060708), @as(u12, 0xabc), @as(i7, -1) }, &.{ - 0xfe, 0xff, 0xff, 0x78, 0x56, 0x34, 0x12, - 8, 7, 6, 5, 4, 3, 2, - 1, 0xbc, 0x0a, 0xff, - }); - try expectBytes(&.{ .{ .kind = .floating }, .{ .kind = .floating }, .{ .kind = .floating } }, .{ @as(f16, 1.0), @as(f32, -2.5), @as(f64, -0.0) }, &.{ 0, 0x3c, 0, 0, 0x20, 0xc0, 0, 0, 0, 0, 0, 0, 0, 0x80 }); +const PendingLog = struct { + site: *const LogSite, + logger: *const LoggerState, + serialized_args: []const u8, +}; - var mutable = [_]u8{ 'a', 0, 'b' }; - const immutable: []const u8 = "hi"; - try expectBytes(&.{ - .{ .kind = .string }, .{ .kind = .string }, .{ .kind = .string }, .{ .kind = .string }, - }, .{ mutable[0..], immutable, "", "Z" }, &.{ - 3, 0, 0, 0, 'a', 0, 'b', 2, 0, 0, 0, 'h', 'i', 0, 0, 0, 0, 1, 0, 0, 0, 'Z', - }); - // Explicitly exercise a mutable slice, not just a pointer to an array. - const mutable_slice: []u8 = &mutable; - try expectBytes(&.{.{ .kind = .string }}, .{mutable_slice}, &.{ 3, 0, 0, 0, 'a', 0, 'b' }); - - const Record = struct { - tag: u8, - count: u32, - nested: struct { amount: f32, label: []const u8 }, - }; - try expectBytes(&.{ .{ .kind = .structure }, .{ .kind = .integer } }, .{ - Record{ .tag = 7, .count = 0x12345678, .nested = .{ .amount = 1.0, .label = "ok" } }, @as(u8, 9), - }, &.{ 7, 0x78, 0x56, 0x34, 0x12, 0, 0, 0x80, 0x3f, 2, 0, 0, 0, 'o', 'k', 9 }); - try expectBytes(&.{.{ .kind = .structure }}, .{struct {}{}}, &.{}); - try expectBytes(&.{}, .{}, &.{}); - - var writer = std.Io.Writer.Allocating.init(std.testing.allocator); - defer writer.deinit(); - const integers = ArgsSerializer{ .ops = &.{.{ .kind = .integer }} }; - try std.testing.expectError(error.IntegerOutOfRange, integers.serialize(.{-1}, &writer.writer)); - try std.testing.expectError(error.IntegerOutOfRange, integers.serialize(.{0x100000000}, &writer.writer)); - try std.testing.expectError(error.InvalidOperationCount, integers.serialize(.{}, &writer.writer)); - try std.testing.expectError(error.InvalidOperationCount, integers.serialize(.{ 1, 2 }, &writer.writer)); - const mismatched = ArgsSerializer{ .ops = &.{ .{ .kind = .integer }, .{ .kind = .floating } } }; - try std.testing.expectError(error.InvalidOperation, mismatched.serialize(.{ 1, @as(u8, 2) }, &writer.writer)); - try std.testing.expectEqual(@as(usize, 0), writer.written().len); - - // A partial/failed write must propagate instead of silently losing bytes. - var small_buffer: [2]u8 = undefined; - var limited = std.Io.Writer.fixed(&small_buffer); - try std.testing.expectError(error.WriteFailed, integers.serialize(.{1}, &limited)); -} - -var gLoggerContext: LoggerContext = undefined; - -pub const LoggerContext = struct { +/// Keep at a stable address. Initialize before starting producers; close and +/// join all producers before deinit/reinitialization. Only one thread may drain, +/// inspect the registries/entries, render to stdout, or deinitialize the context. +pub const LoggerSystem = struct { stdout_buffer: [8192 * 8]u8 = undefined, stdout_file_writer: std.Io.File.Writer = undefined, stdout_writer: *std.Io.Writer = undefined, - + io: std.Io = undefined, arena: std.heap.ArenaAllocator = undefined, backing: std.mem.Allocator = undefined, + payload_allocator: std.mem.Allocator = undefined, + queue_buffer: []PendingLog = undefined, + queue: std.Io.Queue(PendingLog) = undefined, + dropped: std.atomic.Value(u64) = .init(0), - logMap: std.HashMapUnmanaged(LogRef, u32, LogRef.Context, 80) = .empty, - - loggerStates: std.AutoHashMapUnmanaged(*LoggerState, u32) = .empty, - loggerStatesById: std.ArrayList(*LoggerState) = .empty, - - // keyed by id (u32 index) + // Consumer-owned registries; producers only reference static descriptors. + logMap: std.AutoHashMapUnmanaged(*const LogSite, u32) = .empty, + loggerStates: std.AutoHashMapUnmanaged(*const LoggerState, u32) = .empty, + loggerStatesById: std.ArrayList(*const LoggerState) = .empty, logSites: std.ArrayList(LogSite) = .empty, - - serializeWriter: std.Io.Writer.Allocating = undefined, - entries: std.ArrayList(StructuredLog) = .empty, - pub fn insertLoggerStateOrGetId(self: *@This(), state: *LoggerState) u32 { - if (state.id >= 0) { - const id: usize = @intCast(state.id); - if (id < self.loggerStatesById.items.len and self.loggerStatesById.items[id] == state) return @intCast(id); - } - if (self.loggerStates.get(state)) |id| { - return id; + pub const EnqueueError = ArgsSerializer.Error || std.mem.Allocator.Error || error{ QueueFull, Closed }; + + /// Encodes using argument types only. No registry access or shared writer. + /// On success, ownership of the payload transfers to the queue. + /// Site/logger descriptors must outlive all queued and retained events. + pub fn enqueue(self: *@This(), site: *const LogSite, logger: *const LoggerState, args: anytype) EnqueueError!void { + var writer: std.Io.Writer.Allocating = .init(self.payload_allocator); + defer writer.deinit(); + try ArgsSerializer.serialize(args, &writer.writer); + const bytes = try writer.toOwnedSlice(); + errdefer self.payload_allocator.free(bytes); + + const pending: PendingLog = .{ .site = site, .logger = logger, .serialized_args = bytes }; + if (try self.queue.putUncancelable(self.io, &.{pending}, 0) == 0) { + _ = self.dropped.fetchAdd(1, .monotonic); + return error.QueueFull; } + } + + fn getOrRegisterLoggerState(self: *@This(), state: *const LoggerState) !u32 { + if (self.loggerStates.get(state)) |id| return id; + const allocator = self.arena.allocator(); - const rv: u32 = @intCast(self.loggerStatesById.items.len); - self.loggerStates.put(allocator, state, rv) catch @panic("unbounded arena oom"); - self.loggerStatesById.append(allocator, state) catch @panic("unbounded arena saw oom"); - state.id = @intCast(rv); - return rv; + try self.loggerStates.ensureUnusedCapacity(allocator, 1); + try self.loggerStatesById.ensureUnusedCapacity(allocator, 1); + + const id = std.math.cast(u32, self.loggerStatesById.items.len) orelse return error.TooManyLoggers; + self.loggerStatesById.appendAssumeCapacity(state); + self.loggerStates.putAssumeCapacity(state, id); + + return id; } - pub fn getSerializerWriter(self: *@This()) *std.Io.Writer.Allocating { - return &self.serializeWriter; - } - - pub fn insertLogRefOrGetId(self: *@This(), comptime ref: LogRef, idref: *i32, comptime Args: type) u32 { - const site = comptime LogSite.init(ref, Args); - // Cached IDs are valid only in the context that registered them. - if (idref.* >= 0) { - const id: usize = @intCast(idref.*); - if (id < self.logSites.items.len and LogRef.Context.eql(.{}, self.logSites.items[id].source, site.source)) return @intCast(id); - } - if (self.logMap.get(site.source)) |key| { - idref.* = @intCast(key); - return key; - } + fn getOrRegisterSite(self: *@This(), site: *const LogSite) !u32 { + if (self.logMap.get(site)) |id| return id; const allocator = self.arena.allocator(); - const rv: u32 = @intCast(self.logSites.items.len); - self.logSites.append(allocator, site) catch @panic("unbounded arena oom"); - self.logMap.put(allocator, site.source, rv) catch @panic("unbounded arena saw oom"); - idref.* = @intCast(rv); - return rv; + try self.logMap.ensureUnusedCapacity(allocator, 1); + try self.logSites.ensureUnusedCapacity(allocator, 1); + + const id = std.math.cast(u32, self.logSites.items.len) orelse return error.TooManySites; + self.logSites.appendAssumeCapacity(site.*); + self.logMap.putAssumeCapacity(site, id); + + return id; } - pub fn submit(self: *@This(), structuredLog: StructuredLog) !void { - try self.entries.append(self.arena.allocator(), structuredLog); + /// Process at most the queue's capacity so active producers cannot keep a + /// main-thread drain busy indefinitely. Does not wait for new events. + pub fn drain(self: *@This()) !usize { + var count: usize = 0; + + while (count < self.queue_buffer.len) : (count += 1) { + try self.entries.ensureUnusedCapacity(self.arena.allocator(), 1); + var pending: [1]PendingLog = undefined; + const n = self.queue.getUncancelable(self.io, &pending, 0) catch |err| switch (err) { + error.Closed => break, + }; + + if (n == 0) break; + const entry = pending[0]; + + // If registration fails, this dequeued payload must still be freed. + const log = self.accept(entry) catch |err| { + self.payload_allocator.free(entry.serialized_args); + _ = self.dropped.fetchAdd(1, .monotonic); + return err; + }; + self.entries.appendAssumeCapacity(log); + if (entry.logger.stdout) try log.render(self, self.stdout_writer); + } + return count; + } + + fn accept(self: *@This(), pending: PendingLog) !StructuredLog { + return .{ + .serialized_args = pending.serialized_args, + .loggerId = try self.getOrRegisterLoggerState(pending.logger), + .sourceId = try self.getOrRegisterSite(pending.site), + }; + } + + /// Stop accepting events. Already queued events can still be drained. + pub fn close(self: *@This()) void { + self.queue.close(self.io); } pub fn init(self: *@This(), io: std.Io, allocator: std.mem.Allocator) void { - self.stdout_file_writer = .init(.stdout(), io, &self.stdout_buffer); - self.stdout_writer = &self.stdout_file_writer.interface; - - self.logMap = .empty; - self.loggerStates = .empty; - self.loggerStatesById = .empty; - self.logSites = .empty; - self.entries = .empty; - self.backing = allocator; - self.arena = std.heap.ArenaAllocator.init(self.backing); - self.serializeWriter = std.Io.Writer.Allocating.initCapacity(self.arena.allocator(), 1024) catch @panic("unbounded arena oom"); + self.initOptions(io, allocator, .{}); } + pub fn initOptions(self: *@This(), io: std.Io, allocator: std.mem.Allocator, options: LoggerSystemInitOptions) void { + std.debug.assert(options.queue_capacity > 0); + self.* = .{}; + self.io = io; + self.backing = allocator; + self.payload_allocator = options.payload_allocator; + self.arena = std.heap.ArenaAllocator.init(allocator); + self.queue_buffer = allocator.alloc(PendingLog, options.queue_capacity) catch @panic("log queue oom"); + self.queue = .init(self.queue_buffer); + self.stdout_file_writer = .init(.stdout(), io, &self.stdout_buffer); + self.stdout_writer = &self.stdout_file_writer.interface; + } + + /// Producers must have finished. Frees both drained and undrained payloads. pub fn deinit(self: *@This()) void { + self.close(); + var pending: [16]PendingLog = undefined; + while (true) { + const n = self.queue.getUncancelable(self.io, &pending, 0) catch break; + if (n == 0) break; + for (pending[0..n]) |entry| self.payload_allocator.free(entry.serialized_args); + } + for (self.entries.items) |entry| self.payload_allocator.free(entry.serialized_args); + self.backing.free(self.queue_buffer); self.arena.deinit(); } }; pub fn initialize(io: std.Io, allocator: std.mem.Allocator) void { - gLoggerContext.init(io, allocator); + gLoggerSystem.init(io, allocator); +} + +pub fn initializeOptions(io: std.Io, allocator: std.mem.Allocator, options: LoggerSystemInitOptions) void { + gLoggerSystem.initOptions(io, allocator, options); +} + +/// Counts rejected full-queue submissions (including retries) and events lost +/// to consumer registration failures. Safe to read from any producer thread. +pub fn droppedCount() u64 { + return gLoggerSystem.dropped.load(.monotonic); +} + +/// Stop accepting events before joining producer threads. +pub fn close() void { + gLoggerSystem.close(); } pub fn deinit() void { - gLoggerContext.deinit(); + gLoggerSystem.deinit(); } + +/// Call on the consumer/main thread. Does not wait for producers to finish. +pub fn drain() !usize { + return gLoggerSystem.drain(); +} + +/// Consumer-thread checkpoint: drains up to one queue capacity and flushes +/// stdout. Join producers first when a complete final flush is required. pub fn flush() void { - gLoggerContext.stdout_writer.flush() catch {}; + _ = drain() catch @panic("log drain failed"); + gLoggerSystem.stdout_writer.flush() catch {}; } pub const LogRef = struct { @@ -465,8 +487,7 @@ pub const LogRef = struct { pub const LoggerState = struct { name: []const u8, - verbosity: Verbosity, - id: i32 = -1, + verbosity: std.atomic.Value(Verbosity), stdout: bool = false, // mirrors it's output to stdout }; @@ -492,10 +513,10 @@ pub const StructuredLog = struct { /// numbered arguments, escaped braces, scalar formats and constant options. /// Named/dynamic options and custom Zig format methods are unsupported. /// Integer schemas wider than 128 bits are unsupported. - pub fn render(self: @This(), logger: *const LoggerContext, writer: *std.Io.Writer) RenderError!void { + pub fn render(self: @This(), logger: *const LoggerSystem, writer: *std.Io.Writer) RenderError!void { if (self.loggerId >= logger.loggerStatesById.items.len or self.sourceId >= logger.logSites.items.len) return error.InvalidLogReference; const site = logger.logSites.items[self.sourceId]; - const ops = site.serializer.ops; + const ops = site.decoder.ops; var payload = Cursor{ .bytes = self.serialized_args }; for (ops) |op| try skipValue(op, &payload, 0); if (payload.bytes.len != 0) return error.InvalidPayload; @@ -531,15 +552,24 @@ pub const StructuredLog = struct { return result; } + fn boolean(self: *Cursor) RenderError!bool { + return switch ((try self.take(1))[0]) { + 0 => false, + 1 => true, + else => error.InvalidPayload, + }; + } + fn string(self: *Cursor) RenderError![]const u8 { const len: usize = @intCast(try self.integer(4)); return self.take(len); } }; - fn skipValue(op: ArgsSerializerOp, cursor: *Cursor, depth: usize) RenderError!void { + fn skipValue(op: ArgsDecoderOp, cursor: *Cursor, depth: usize) RenderError!void { if (depth > 64) return error.InvalidSchema; switch (op.kind) { + .boolean => _ = try cursor.boolean(), .integer, .floating => { if (op.bits > 128) return error.InvalidSchema; if (op.kind == .floating) switch (op.bits) { @@ -553,10 +583,11 @@ pub const StructuredLog = struct { } } - fn renderValue(op: ArgsSerializerOp, cursor: *Cursor, format: RenderOp.Format, options: std.fmt.Options, writer: *std.Io.Writer, depth: usize) RenderError!void { + fn renderValue(op: ArgsDecoderOp, cursor: *Cursor, format: RenderOp.Format, options: std.fmt.Options, writer: *std.Io.Writer, depth: usize) RenderError!void { if (depth > 64) return error.InvalidSchema; if (!format.supports(op.kind)) return error.UnsupportedFormat; switch (op.kind) { + .boolean => try writer.printValue("", options, try cursor.boolean(), std.fmt.default_max_depth), .integer => { const base: u8 = switch (format) { .any, .decimal => 10, @@ -626,48 +657,33 @@ pub const StructuredLog = struct { pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptions) type { return struct { + // Name/stdout are immutable once producers start. Change verbosity via + // setVerbosity so concurrent producers always use an atomic load. pub var loggerState: LoggerState = .{ .name = LoggerName, - .verbosity = opts.verbosity, + .verbosity = .init(opts.verbosity), + .stdout = opts.has_stdout, }; + pub fn setVerbosity(v: Verbosity) void { + loggerState.verbosity.store(v, .monotonic); + } + + pub fn tryAddLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) LoggerSystem.EnqueueError!void { + if (@backingInt(loggerState.verbosity.load(.monotonic)) > @backingInt(v)) return; + + const FmtSite = struct { + pub const site = LogSite.init(LogRef.fromSrcFmt(s, fmt), @TypeOf(args)); + }; + try gLoggerSystem.enqueue(&FmtSite.site, &loggerState, args); + } + + /// Drop new events when full; callers needing retries can use tryAddLog. pub fn addLog(comptime s: std.builtin.SourceLocation, v: Verbosity, comptime fmt: []const u8, args: anytype) void { - const FmtState = struct { - pub const FMT = fmt; - pub const source = s; - pub var index: i32 = -1; + tryAddLog(s, v, fmt, args) catch |err| switch (err) { + error.QueueFull, error.Closed => {}, + else => @panic("log serialization failed"), }; - - // create a hash of the s: builtin sourcelocation - const ref = comptime LogRef.fromSrcFmt(s, fmt); - const sourceId = gLoggerContext.insertLogRefOrGetId(ref, &FmtState.index, @TypeOf(args)); - const loggerId = gLoggerContext.insertLoggerStateOrGetId(&loggerState); - - if (@backingInt(loggerState.verbosity) > @backingInt(v)) { - return; - } - - const debug = true; - if (debug) { - gLoggerContext.stdout_writer.print("[{d}] [{d}] ", .{ loggerId, sourceId }) catch @panic("io error"); - gLoggerContext.stdout_writer.print(fmt ++ "\n", args) catch @panic("io error"); - gLoggerContext.stdout_writer.flush() catch @panic("debug io error"); - } - - // stash the logs into the logger's in-memory log - const serializer = gLoggerContext.logSites.items[sourceId].serializer; - const writer = gLoggerContext.getSerializerWriter(); - writer.writer.end = 0; - serializer.serialize(args, &writer.writer) catch @panic("log serialization failed"); - const serialized_args = gLoggerContext.arena.allocator().dupe(u8, writer.written()) catch @panic("unbounded arena oom"); - - const structuredLog = StructuredLog{ - .serialized_args = serialized_args, - .loggerId = loggerId, - .sourceId = sourceId, - }; - - gLoggerContext.submit(structuredLog) catch @panic("unbounded arena oom"); } }; } @@ -675,104 +691,152 @@ pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptio const std = @import("std"); const builtin = @import("builtin"); -test "init logger" { - initialize(std.testing.io, std.testing.allocator); - defer deinit(); - - const TestLogger = DeclareLogger("Testing", .{}); - TestLogger.addLog(@src(), .log, "testing", .{}); - TestLogger.addLog(@src(), .log, "testing", .{}); - TestLogger.addLog(@src(), .log, "testing", .{}); - TestLogger.addLog(@src(), .log, "testing", .{}); - - flush(); -} - -test "structured log render" { - const check = struct { - fn run(comptime fmt: []const u8, args: anytype) !void { - var logger: LoggerContext = .{}; - logger.init(std.testing.io, std.testing.allocator); - defer logger.deinit(); - var state: LoggerState = .{ .name = "render", .verbosity = .log }; - const logger_id = logger.insertLoggerStateOrGetId(&state); - var id: i32 = -1; - const source_id = logger.insertLogRefOrGetId(LogRef.fromSrcFmt(@src(), fmt), &id, @TypeOf(args)); - var payload: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer payload.deinit(); - try logger.logSites.items[source_id].serializer.serialize(args, &payload.writer); +test "structured logging end to end" { + const Logger = DeclareLogger("normal", .{}); + const Record = struct { id: i16, enabled: bool, position: struct { x: f32, label: []const u8 } }; + const emit = struct { + fn log(comptime fmt: []const u8, args: anytype) !void { + const before = gLoggerSystem.entries.items.len; + try Logger.tryAddLog(@src(), .log, fmt, args); + try std.testing.expectEqual(before, gLoggerSystem.entries.items.len); + try std.testing.expectEqual(@as(usize, 1), try drain()); + const entry = gLoggerSystem.entries.items[before]; var output: std.Io.Writer.Allocating = .init(std.testing.allocator); defer output.deinit(); - const entry: StructuredLog = .{ .loggerId = logger_id, .sourceId = source_id, .serialized_args = payload.written() }; - // Rendering must use stored instructions, not reparse the format. - logger.logSites.items[source_id].source.fmt = "{"; - try entry.render(&logger, &output.writer); + try entry.render(&gLoggerSystem, &output.writer); var expected: std.Io.Writer.Allocating = .init(std.testing.allocator); defer expected.deinit(); - try expected.writer.print("[0] [0] " ++ fmt ++ "\n", args); + try expected.writer.print("[{d}] [{d}] ", .{ entry.loggerId, entry.sourceId }); + try expected.writer.print(fmt ++ "\n", args); try std.testing.expectEqualStrings(expected.written(), output.written()); - - for (0..payload.written().len) |len| { - var truncated = entry; - truncated.serialized_args = entry.serialized_args[0..len]; - try std.testing.expectError(error.InvalidPayload, truncated.render(&logger, &output.writer)); - } - var invalid = entry; - invalid.sourceId = 999; - try std.testing.expectError(error.InvalidLogReference, invalid.render(&logger, &output.writer)); - invalid = entry; - invalid.loggerId = 999; - try std.testing.expectError(error.InvalidLogReference, invalid.render(&logger, &output.writer)); - var empty_buffer: [0]u8 = .{}; - var failing = std.Io.Writer.fixed(&empty_buffer); - try std.testing.expectError(error.WriteFailed, entry.render(&logger, &failing)); } - }.run; - try check("literal {{braces}}", .{}); - try check("{{{0x}}} {} {1d} {}", .{ @as(u32, 31), @as(i16, -2) }); - try check("{s:*^8} {d:06}", .{ "hi", @as(u16, 23) }); - try check("{} {d} {x:0>8} {X} {b} {o}", .{ 42, @as(i7, -5), @as(u32, 0x1234), @as(u128, 0xabcdef), @as(u12, 0xabc), @as(i16, -9) }); - try check("{d} {d}", .{ @as(u128, std.math.maxInt(u128)), @as(i128, std.math.minInt(i128)) }); - try check("{d:.2} {e} {} {x}", .{ 1.25, @as(f32, -2.5), @as(f64, -0.0), @as(f16, 1.5) }); - try check("{d} {e}", .{ @as(f80, 1.25), @as(f128, 2.5) }); - try check("{s:*>6} {s} {any}", .{ "hi", "", @as([]const u8, "a\x00b") }); - try check("{1s} {0d} {1s}", .{ @as(u16, 23), "ok" }); - const Record = struct { id: i16, position: struct { x: f32, label: []const u8 } }; - try check("{any} {any}", .{ Record{ .id = -4, .position = .{ .x = 1.25, .label = "pos" } }, .{ @as(u8, 1), @as(f32, 2) } }); - try check("{any}", .{struct {}{}}); -} - -test "structured log render malformed metadata and payload" { - var logger: LoggerContext = .{}; - logger.init(std.testing.io, std.testing.allocator); - defer logger.deinit(); - var state: LoggerState = .{ .name = "render", .verbosity = .log }; - _ = logger.insertLoggerStateOrGetId(&state); - var id: i32 = -1; - _ = logger.insertLogRefOrGetId(LogRef.fromSrcFmt(@src(), "{d}"), &id, @TypeOf(.{@as(u32, 1)})); - var output: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer output.deinit(); - var entry: StructuredLog = .{ .loggerId = 0, .sourceId = 0, .serialized_args = &.{ 1, 0, 0, 0, 99 } }; - try std.testing.expectError(error.InvalidPayload, entry.render(&logger, &output.writer)); - entry.serialized_args = entry.serialized_args[0..4]; - logger.logSites.items[0].render_ops = &.{.{ .argument = .{ .index = 3, .format = .decimal } }}; - try std.testing.expectError(error.InvalidFormat, entry.render(&logger, &output.writer)); - logger.logSites.items[0].render_ops = &.{.{ .argument = .{ .index = 0, .format = .string } }}; - try std.testing.expectError(error.UnsupportedFormat, entry.render(&logger, &output.writer)); - logger.logSites.items[0].serializer = .{ .ops = &.{.{ .kind = .integer, .bits = 256 }} }; - try std.testing.expectError(error.InvalidSchema, entry.render(&logger, &output.writer)); -} - -test "structured logger captures and renders after reinitialization" { - const Logger = DeclareLogger("roundtrip", .{}); + }.log; + // Exercise static site reuse across independent system lifetimes. for (0..2) |_| { - initialize(std.testing.io, std.testing.allocator); + initializeOptions(std.testing.io, std.testing.allocator, .{ .queue_capacity = 1, .payload_allocator = std.testing.allocator }); defer deinit(); - for (0..3) |i| Logger.addLog(@src(), .log, "event {d}: {s}", .{ @as(u32, @intCast(i)), "ok" }); - try std.testing.expectEqual(@as(usize, 1), gLoggerContext.logSites.items.len); - var output: std.Io.Writer.Allocating = .init(std.testing.allocator); - defer output.deinit(); - for (gLoggerContext.entries.items) |entry| try entry.render(&gLoggerContext, &output.writer); - try std.testing.expectEqualStrings("[0] [0] event 0: ok\n[0] [0] event 1: ok\n[0] [0] event 2: ok\n", output.written()); + Logger.setVerbosity(.warn); + Logger.addLog(@src(), .log, "filtered", .{}); + try std.testing.expectEqual(@as(usize, 0), try drain()); + Logger.setVerbosity(.verbose); + try emit("literal {{braces}}", .{}); + try emit("{1s:*>6} {0d} {1s}", .{ @as(i16, -7), "hello" }); + for (0..2) |_| try emit("{} {x:08} {X} {b} {o} {d:.2} {e} {x} {any}", .{ + 42, @as(u32, 255), @as(u8, 255), @as(u12, 7), @as(i7, -3), 1.25, @as(f64, -2.5), @as(f16, 1.5), + Record{ .id = -2, .enabled = true, .position = .{ .x = 3.5, .label = "owned" } }, + }); + try emit("{} {any:>8}", .{ true, false }); + const bool_entry = gLoggerSystem.entries.items[gLoggerSystem.entries.items.len - 1]; + try std.testing.expectEqualSlices(u8, &.{ 1, 0 }, bool_entry.serialized_args); + try std.testing.expectEqual(@as(usize, 4), gLoggerSystem.logSites.items.len); + try std.testing.expectEqual(@as(usize, 1), gLoggerSystem.loggerStatesById.items.len); + Logger.addLog(@src(), .warn, "queued", .{}); + try std.testing.expectError(error.QueueFull, Logger.tryAddLog(@src(), .warn, "full", .{})); + try std.testing.expectEqual(@as(u64, 1), droppedCount()); + flush(); + Logger.addLog(@src(), .warn, "cleanup {s}", .{"undrained payload"}); + close(); + try std.testing.expectError(error.Closed, Logger.tryAddLog(@src(), .warn, "closed", .{})); + } +} + +test "concurrent logging with bounded queue and simultaneous main thread drain" { + const A = DeclareLogger("producer-A", .{}); + const B = DeclareLogger("producer-B", .{}); + const Worker = struct { + fn run(id: u32, start: *std.Io.Event, stop: *std.atomic.Value(bool), done: *std.atomic.Value(u32), failed: *std.atomic.Value(bool)) void { + defer _ = done.fetchAdd(1, .release); + start.waitUncancelable(std.testing.io); + for (0..256) |seq| { + var text: [4]u8 = @splat(@intCast('a' + id)); + while (!stop.load(.acquire)) { + const result = if (seq % 2 == 0) + A.tryAddLog(@src(), .log, "A {d}:{d} {s}", .{ id, @as(u32, @intCast(seq)), text[0..] }) + else + B.tryAddLog(@src(), .warn, "B {d}:{d} {s}", .{ id, @as(u32, @intCast(seq)), text[0..] }); + result catch |err| switch (err) { + error.QueueFull => { + std.Thread.yield() catch {}; + continue; + }, + else => { + failed.store(true, .release); + return; + }, + }; + break; + } + @memset(&text, 0xdd); + if (stop.load(.acquire)) return; + } + } + }; + gLoggerSystem.initOptions(std.testing.io, std.testing.allocator, .{ .queue_capacity = 8, .payload_allocator = std.testing.allocator }); + defer deinit(); + var start: std.Io.Event = .unset; + var stop: std.atomic.Value(bool) = .init(false); + var done: std.atomic.Value(u32) = .init(0); + var failed: std.atomic.Value(bool) = .init(false); + var threads: [4]std.Thread = undefined; + var spawned: usize = 0; + defer { + stop.store(true, .release); + start.set(std.testing.io); + for (threads[0..spawned]) |thread| thread.join(); + } + for (&threads, 0..) |*thread, id| { + thread.* = try std.Thread.spawn(.{}, Worker.run, .{ @as(u32, @intCast(id)), &start, &stop, &done, &failed }); + spawned += 1; + } + start.set(std.testing.io); + while (done.load(.acquire) != threads.len) { + _ = try drain(); + std.Thread.yield() catch {}; + } + _ = try drain(); + try std.testing.expect(!failed.load(.acquire)); + try std.testing.expectEqual(@as(usize, 1024), gLoggerSystem.entries.items.len); + try std.testing.expectEqual(@as(usize, 2), gLoggerSystem.logSites.items.len); + try std.testing.expectEqual(@as(usize, 2), gLoggerSystem.loggerStatesById.items.len); + var next: [4]u32 = @splat(0); + for (gLoggerSystem.entries.items) |entry| { + var cursor: StructuredLog.Cursor = .{ .bytes = entry.serialized_args }; + const id: usize = @intCast(try cursor.integer(4)); + try std.testing.expect(id < next.len); + const seq: u32 = @intCast(try cursor.integer(4)); + try std.testing.expectEqual(next[id], seq); + next[id] += 1; + const text: [4]u8 = @splat(@intCast('a' + id)); + var output: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer output.deinit(); + try entry.render(&gLoggerSystem, &output.writer); + var expected: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer expected.deinit(); + try expected.writer.print("[{d}] [{d}] {s} {d}:{d} {s}\n", .{ entry.loggerId, entry.sourceId, if (seq % 2 == 0) "A" else "B", id, seq, text }); + try std.testing.expectEqualStrings(expected.written(), output.written()); + } + for (next) |n| try std.testing.expectEqual(@as(u32, 256), n); +} + +test "testing" { + const xxd = @import("xxd.zig"); + + initialize(std.testing.io, std.testing.allocator); + defer deinit(); + const Logger = DeclareLogger("mylogger", .{ .verbosity = .verbose }); + Logger.addLog(@src(), .log, "who doesn't {} {s} 2 + 2 is {d}", .{ true, "dragons", 4 }); + const drained = try gLoggerSystem.drain(); + var writer = std.Io.Writer.Allocating.init(std.testing.allocator); + + std.debug.print("drained {d} entries\n", .{drained}); + for (gLoggerSystem.entries.items) |item| { + try xxd.xxdWriteAscii(&writer.writer, item.serialized_args, .{}); + try writer.writer.print("\n", .{}); + try item.render(&gLoggerSystem, &writer.writer); + + var x = writer.toArrayList(); + defer x.deinit(std.testing.allocator); + + std.debug.print("{s}\n", .{x.items}); } } diff --git a/engine/lib/p2/src/structures/xxd.zig b/engine/lib/p2/src/structures/xxd.zig new file mode 100644 index 0000000..f128403 --- /dev/null +++ b/engine/lib/p2/src/structures/xxd.zig @@ -0,0 +1,105 @@ +const std = @import("std"); + +pub const Endian = enum { + big, + little, +}; + +pub const XxdOptions = struct { + wordSize: u32 = 8, // bits; must be a nonzero multiple of 8 + // Preserve the existing convention: little prints bytes in input order; + // big reverses the bytes within each word. ASCII always uses input order. + endian: Endian = .little, + wordsPerGroup: u32 = 2, + groupsPerLine: u32 = 8, + groupSplit: u32 = 4, // extra space every N groups; 0 disables it + showAddress: bool = true, + showAscii: bool = false, +}; + +pub const Error = std.Io.Writer.Error || error{InvalidOptions}; + +/// Writes a hex dump. Does not allocate or flush the caller's writer. +pub fn xxdWrite(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) Error!void { + if (options.wordSize == 0 or options.wordSize % 8 != 0 or options.wordsPerGroup == 0 or options.groupsPerLine == 0) return error.InvalidOptions; + const bytes_per_word: usize = options.wordSize / 8; + const words_per_line = std.math.mul(usize, options.wordsPerGroup, options.groupsPerLine) catch return error.InvalidOptions; + const bytes_per_line = std.math.mul(usize, bytes_per_word, words_per_line) catch return error.InvalidOptions; + + var offset: usize = 0; + while (offset < bytes.len) { + const row = bytes[offset..][0..@min(bytes_per_line, bytes.len - offset)]; + if (options.showAddress) try writer.print("{x:0>8}: ", .{offset}); + const word_count = if (options.showAscii) words_per_line else (row.len - 1) / bytes_per_word + 1; + for (0..word_count) |word_index| { + if (word_index > 0 and word_index % options.wordsPerGroup == 0) { + try writer.writeByte(' '); + const group_index = word_index / options.wordsPerGroup; + if (options.groupSplit != 0 and group_index % options.groupSplit == 0) { + try writer.writeByte(' '); + } + } + const start = @min(word_index * bytes_per_word, row.len); + const word = row[start..][0..@min(bytes_per_word, row.len - start)]; + for (0..word.len) |i| { + const index = if (options.endian == .little) i else word.len - 1 - i; + try writeByteAsHex(word[index], writer); + } + if (options.showAscii) { + // Pad missing bytes so every row's ASCII starts in the same column. + for (word.len..bytes_per_word) |_| try writer.writeAll(" "); + } + } + if (options.showAscii) { + try writer.writeAll(" | "); + for (row) |byte| try writer.writeByte(if (byte >= 0x20 and byte <= 0x7e) byte else '.'); + } + try writer.writeByte('\n'); + offset += row.len; + } +} + +/// Hex plus printable ASCII, with '.' for control and non-ASCII bytes. +/// For separate byte columns, set wordsPerGroup = 1 and groupsPerLine = 16. +pub fn xxdWriteAscii(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) Error!void { + var ascii_options = options; + ascii_options.showAscii = true; + try xxdWrite(writer, bytes, ascii_options); +} + +inline fn writeByteAsHex(byte: u8, writer: *std.Io.Writer) std.Io.Writer.Error!void { + const digits = "0123456789ABCDEF"; + try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] }); +} + +test "hex and ASCII dump layout" { + var output: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer output.deinit(); + const options: XxdOptions = .{ .wordsPerGroup = 1, .groupsPerLine = 4, .groupSplit = 2 }; + try xxdWriteAscii(&output.writer, "AB\x00\t~\x7f\x80!x", options); + try std.testing.expectEqualStrings( + "00000000: 41 42 00 09 | AB..\n" ++ + "00000004: 7E 7F 80 21 | ~..!\n" ++ + "00000008: 78" ++ " " ++ " | x\n", + output.written(), + ); + output.writer.end = 0; + try xxdWriteAscii(&output.writer, "ABC", .{ .wordSize = 16, .wordsPerGroup = 1, .groupsPerLine = 2, .groupSplit = 0, .endian = .big, .showAddress = false }); + try std.testing.expectEqualStrings("4241 43 | ABC\n", output.written()); + output.writer.end = 0; + try xxdWrite(&output.writer, "ABCDE", .{ .wordSize = 16, .wordsPerGroup = 1, .groupsPerLine = 2, .groupSplit = 0, .showAddress = false }); + try std.testing.expectEqualStrings("4142 4344\n45\n", output.written()); +} + +test "hex dump empty input options and writer errors" { + var output: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer output.deinit(); + try xxdWriteAscii(&output.writer, "", .{}); + try std.testing.expectEqual(@as(usize, 0), output.written().len); + for ([_]XxdOptions{ .{ .wordSize = 0 }, .{ .wordSize = 7 }, .{ .wordsPerGroup = 0 }, .{ .groupsPerLine = 0 } }) |options| { + try std.testing.expectError(error.InvalidOptions, xxdWrite(&output.writer, "x", options)); + } + var buffer: [1]u8 = undefined; + var fixed: std.Io.Writer = .fixed(&buffer); + try std.testing.expectError(error.WriteFailed, xxdWriteAscii(&fixed, "x", .{})); +} diff --git a/engine/lib/p2/src/utils/xxd.zig b/engine/lib/p2/src/utils/xxd.zig deleted file mode 100644 index 4f24f61..0000000 --- a/engine/lib/p2/src/utils/xxd.zig +++ /dev/null @@ -1,102 +0,0 @@ -const std = @import("std"); - -const Endian = enum { - big, - little, -}; - -pub const XxdOptions = struct { - wordSize: u32 = 8, // in bits - endian: Endian = .little, - wordsPerGroup: u32 = 2, // in number of words - groupsPerLine: u32 = 8, // number of bytes per word - groupSplit: u32 = 4, // insert a double space every x number of - showAddress: bool = true, -}; - -pub fn xxdWrite( - writer: anytype, - bytes: []const u8, - options: XxdOptions, -) !void { - var wordBuffer: [16]u8 = undefined; - var wordOffset: usize = 0; - - const bytesPerWord = options.wordSize / 8; - - var wordInGroup: usize = 0; - var groupInLine: usize = 0; - - for (bytes, 0..) |byte, index| { - if (wordInGroup == options.wordsPerGroup) { - if ((groupInLine + 1) % options.groupSplit == 0 and wordInGroup == options.wordsPerGroup) { - try writer.writeByte(' '); - } - - try writer.writeByte(' '); - - wordInGroup = 0; - groupInLine += 1; - - if (groupInLine == options.groupsPerLine) { - try writer.writeByte('\n'); - groupInLine = 0; - } - } - - if (options.showAddress) { - if (wordInGroup == 0 and wordOffset == 0 and groupInLine == 0) { - try writer.print("{x:6.0}: ", .{index}); - } - } - - wordBuffer[wordOffset] = byte; - wordOffset += 1; - if (wordOffset == bytesPerWord) { - // write out the word into the reader according to endian - var wordOffsetIndex: usize = 0; - while (wordOffsetIndex < bytesPerWord) : (wordOffsetIndex += 1) { - const wordByte = if (options.endian == .little) - wordBuffer[wordOffsetIndex] - else - wordBuffer[bytesPerWord - 1 - wordOffsetIndex]; - - try writeByteAsHex(wordByte, writer); - } - wordOffset = 0; - } - - wordInGroup += 1; - } - - _ = try writer.write(".\n"); -} - -inline fn writeByteAsHex(byte: u8, writer: anytype) !void { - const hex = byteAsHex(byte); - try writer.writeByte(hex[1]); - try writer.writeByte(hex[0]); -} - -inline fn byteAsHex(byte: u8) [2]u8 { - var rv: [2]u8 = undefined; - rv[1] = nibbleAsHex(byte >> 4); - rv[0] = nibbleAsHex(byte & 0xF); - - return rv; -} - -fn nibbleAsHex(nib: u8) u8 { - if (nib < 10) - return '0' + nib; - return 'A' - 10 + nib; -} - -test "testing all" { - std.debug.print("\n", .{}); - const writer = std.io.getStdOut().writer(); - try writeByteAsHex(0x2f, writer); - std.debug.print("\n\n", .{}); - try xxdWrite(writer, &[_]u8{ 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22, 0xab, 0xf2, 0x21, 0x22, 0x43, 0x44, 0x12, 0x33, 0x12, 0x42, 0x22 }, .{}); - std.debug.print("\n", .{}); -}