diff --git a/engine/lib/p2/src/structures/structured-logging.zig b/engine/lib/p2/src/structures/structured-logging.zig index abc25a9..5baa8af 100644 --- a/engine/lib/p2/src/structures/structured-logging.zig +++ b/engine/lib/p2/src/structures/structured-logging.zig @@ -16,11 +16,54 @@ pub const ArgsSerializerOpKind = enum { pub const ArgsSerializerOp = struct { kind: ArgsSerializerOpKind, + bits: u16 = 0, + signed: bool = false, + fields: []const Field = &.{}, + is_tuple: bool = false, + + pub const Field = struct { name: []const u8, op: ArgsSerializerOp }; }; pub const ArgsSerializer = struct { ops: []const ArgsSerializerOp, + /// Static metadata can be persisted as values; no encoder function pointers. + pub fn fromArgs(comptime Args: type) ArgsSerializer { + const ops = comptime blk: { + const types = @typeInfo(Args).@"struct".field_types; + var result: [types.len]ArgsSerializerOp = 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) }; + switch (@typeInfo(T)) { + .comptime_int => op.bits = 32, + .comptime_float => op.bits = 64, + .int => |info| { + op.bits = info.bits; + op.signed = info.signedness == .signed; + }, + .float => |info| op.bits = info.bits, + .@"struct" => |info| { + const fields = comptime blk: { + var result: [info.field_names.len]ArgsSerializerOp.Field = undefined; + for (info.field_names, info.field_types, 0..) |name, F, i| { + result[i] = .{ .name = name, .op = schemaFor(F) }; + } + break :blk result; + }; + op.fields = &fields; + op.is_tuple = info.is_tuple; + }, + else => {}, + } + return op; + } + pub const Error = std.Io.Writer.Error || error{ InvalidOperationCount, InvalidOperation, @@ -94,6 +137,126 @@ pub const ArgsSerializer = struct { } }; +/// Data-only rendering instructions; persist their values and string contents, +/// not the in-memory slice pointers or union layout. +pub const RenderOp = union(enum) { + literal: []const u8, + argument: struct { + index: usize, + format: Format, + options: std.fmt.Options = .{}, + }, + + pub const Format = enum { + any, + decimal, + scientific, + hex_lower, + hex_upper, + binary, + octal, + string, + + fn parse(comptime spec: []const u8) Format { + if (spec.len == 0 or std.mem.eql(u8, spec, "any")) return .any; + const names = .{ "d", "e", "x", "X", "b", "o", "s" }; + const formats = [_]Format{ .decimal, .scientific, .hex_lower, .hex_upper, .binary, .octal, .string }; + inline for (names, formats) |name, format| { + if (std.mem.eql(u8, spec, name)) return format; + } + @compileError("Unsupported structured log format: " ++ spec); + } + + fn supports(self: Format, kind: ArgsSerializerOpKind) bool { + return switch (kind) { + .integer => switch (self) { + .any, .decimal, .hex_lower, .hex_upper, .binary, .octal => true, + else => false, + }, + .floating => switch (self) { + .any, .decimal, .scientific, .hex_lower, .hex_upper => true, + else => false, + }, + .string => self == .any or self == .string, + .structure => self == .any, + }; + } + }; +}; + +pub const LogSite = struct { + source: LogRef, + serializer: ArgsSerializer, + render_ops: []const RenderOp, + + pub fn init(comptime source: LogRef, comptime Args: type) LogSite { + var ref = source; + ref.args_type = @typeName(Args); + return .{ + .source = ref, + .serializer = ArgsSerializer.fromArgs(Args), + .render_ops = comptime buildRenderOps(source.fmt, Args), + }; + } + + fn constantOption(comptime spec: std.fmt.Specifier) ?usize { + return switch (spec) { + .none => null, + .number => |n| n, + .named => @compileError("Dynamic structured log format options are unsupported"), + }; + } + + fn buildRenderOps(comptime fmt: []const u8, comptime Args: type) []const RenderOp { + @setEvalBranchQuota(10000 + fmt.len * 1000); + const types = @typeInfo(Args).@"struct".field_types; + if (types.len > @bitSizeOf(std.fmt.ArgSetType)) @compileError("32 log arguments max are supported"); + var args: std.fmt.ArgState = .{ .args_len = types.len }; + var ops: []const RenderOp = &.{}; + var literal: []const u8 = ""; + var i: usize = 0; + while (i < fmt.len) { + const start = i; + while (i < fmt.len and fmt[i] != '{' and fmt[i] != '}') : (i += 1) {} + literal = literal ++ fmt[start..i]; + if (i == fmt.len) break; + if (i + 1 < fmt.len and fmt[i + 1] == fmt[i]) { + literal = literal ++ fmt[i .. i + 1]; + i += 2; + continue; + } + if (fmt[i] == '}') @compileError("Missing opening { in log format"); + if (literal.len != 0) { + ops = ops ++ .{RenderOp{ .literal = literal }}; + literal = ""; + } + const end = std.mem.findScalarPos(u8, fmt, i + 1, '}') orelse @compileError("Missing closing } in log format"); + const placeholder = std.fmt.Placeholder.parse(fmt[i + 1 .. end]); + const index = args.nextArg(switch (placeholder.arg) { + .none => null, + .number => |n| n, + .named => @compileError("Named structured log arguments are unsupported"), + }) orelse @compileError("Log argument index out of range"); + const format = RenderOp.Format.parse(placeholder.specifier_arg); + if (!format.supports(ArgsSerializer.kindFor(types[index]))) @compileError("Log format does not match argument type"); + ops = ops ++ .{RenderOp{ .argument = .{ + .index = index, + .format = format, + .options = .{ + .width = constantOption(placeholder.width), + .precision = constantOption(placeholder.precision), + .fill = placeholder.fill, + .alignment = placeholder.alignment, + }, + } }}; + i = end + 1; + } + if (literal.len != 0) ops = ops ++ .{RenderOp{ .literal = literal }}; + if (args.hasUnusedArgs()) @compileError("Unused structured log argument"); + return ops; + } +}; + pub const Verbosity = enum(u8) { verbose, log, @@ -183,19 +346,22 @@ pub const LoggerContext = struct { backing: std.mem.Allocator = undefined, logMap: std.HashMapUnmanaged(LogRef, u32, LogRef.Context, 80) = .empty, - logMapById: std.ArrayList(LogRef) = .empty, loggerStates: std.AutoHashMapUnmanaged(*LoggerState, u32) = .empty, loggerStatesById: std.ArrayList(*LoggerState) = .empty, // keyed by id (u32 index) - serializers: std.ArrayList(ArgsSerializer) = .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 > -1) { - return @intCast(state.id); + 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; } @@ -204,34 +370,51 @@ pub const LoggerContext = struct { 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; } - pub fn insertLogRefOrGetId(self: *@This(), ref: LogRef, idref: *i32) u32 { - if (idref.* > -1) { - return @intCast(idref.*); - } + pub fn getSerializerWriter(self: *@This()) *std.Io.Writer.Allocating { + return &self.serializeWriter; + } - if (self.logMap.get(ref)) |key| { + 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; } const allocator = self.arena.allocator(); - const rv: u32 = @intCast(self.logMapById.items.len); - self.logMapById.append(allocator, ref) catch @panic("unbounded arena saw oom"); - self.logMap.put(allocator, ref, rv) catch @panic("unbounded arena saw oom"); + 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; } + pub fn submit(self: *@This(), structuredLog: StructuredLog) !void { + try self.entries.append(self.arena.allocator(), structuredLog); + } + 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"); } pub fn deinit(self: *@This()) void { @@ -254,18 +437,20 @@ pub const LogRef = struct { line: u32, file: []const u8, fmt: []const u8, + args_type: []const u8 = "", pub const Context = struct { pub fn hash(_: @This(), key: LogRef) u64 { var hasher = std.hash.Wyhash.init(0); hasher.update(key.file); hasher.update(std.mem.asBytes(&key.line)); - hasher.update(std.mem.asBytes(&key.fmt)); + hasher.update(key.fmt); + hasher.update(key.args_type); return hasher.final(); } pub fn eql(_: @This(), a: LogRef, b: LogRef) bool { - return a.line == b.line and std.mem.eql(u8, a.file, b.file); + return a.line == b.line and std.mem.eql(u8, a.file, b.file) and std.mem.eql(u8, a.fmt, b.fmt) and std.mem.eql(u8, a.args_type, b.args_type); } }; @@ -290,6 +475,155 @@ pub const LoggerOptions = struct { has_stdout: bool = false, }; +pub const StructuredLog = struct { + serialized_args: []const u8, // not a string + loggerId: u32, + sourceId: u32, + + pub const RenderError = std.Io.Writer.Error || error{ + InvalidLogReference, + InvalidSchema, + InvalidPayload, + InvalidFormat, + UnsupportedFormat, + }; + + /// Renders from runtime metadata and payload only. Supports sequential and + /// 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 { + 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; + var payload = Cursor{ .bytes = self.serialized_args }; + for (ops) |op| try skipValue(op, &payload, 0); + if (payload.bytes.len != 0) return error.InvalidPayload; + + try writer.print("[{d}] [{d}] ", .{ self.loggerId, self.sourceId }); + for (site.render_ops) |render_op| switch (render_op) { + .literal => |text| try writer.writeAll(text), + .argument => |arg| { + if (arg.index >= ops.len) return error.InvalidFormat; + var argument = Cursor{ .bytes = self.serialized_args }; + for (ops[0..arg.index]) |op| try skipValue(op, &argument, 0); + try renderValue(ops[arg.index], &argument, arg.format, arg.options, writer, 0); + }, + }; + try writer.writeByte('\n'); + } + + const Cursor = struct { + bytes: []const u8, + + fn take(self: *Cursor, count: usize) RenderError![]const u8 { + if (count > self.bytes.len) return error.InvalidPayload; + const result = self.bytes[0..count]; + self.bytes = self.bytes[count..]; + return result; + } + + fn integer(self: *Cursor, count: usize) RenderError!u128 { + if (count > 16) return error.InvalidSchema; + const bytes = try self.take(count); + var result: u128 = 0; + for (bytes, 0..) |byte, i| result |= @as(u128, byte) << @intCast(i * 8); + return result; + } + + 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 { + if (depth > 64) return error.InvalidSchema; + switch (op.kind) { + .integer, .floating => { + if (op.bits > 128) return error.InvalidSchema; + if (op.kind == .floating) switch (op.bits) { + 16, 32, 64, 80, 128 => {}, + else => return error.InvalidSchema, + }; + _ = try cursor.take((@as(usize, op.bits) + 7) / 8); + }, + .string => _ = try cursor.string(), + .structure => for (op.fields) |field| try skipValue(field.op, cursor, depth + 1), + } + } + + fn renderValue(op: ArgsSerializerOp, 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) { + .integer => { + const base: u8 = switch (format) { + .any, .decimal => 10, + .hex_lower, .hex_upper => 16, + .binary => 2, + .octal => 8, + else => return error.UnsupportedFormat, + }; + const case: std.fmt.Case = if (format == .hex_upper) .upper else .lower; + const count = (@as(usize, op.bits) + 7) / 8; + var raw = try cursor.integer(count); + if (op.signed and count > 0) { + const sign = @as(u128, 1) << @intCast(count * 8 - 1); + if (raw & sign != 0 and count < 16) raw |= (~@as(u128, 0)) << @intCast(count * 8); + try writer.printInt(@as(i128, @bitCast(raw)), base, case, options); + } else { + try writer.printInt(raw, base, case, options); + } + }, + .floating => { + const mode: std.fmt.Number.Mode = switch (format) { + .any, .decimal => .decimal, + .scientific => .scientific, + .hex_lower, .hex_upper => .hex, + else => return error.UnsupportedFormat, + }; + const raw = try cursor.integer((@as(usize, op.bits) + 7) / 8); + inline for (.{ f16, f32, f64, f80, f128 }) |F| { + if (op.bits == @bitSizeOf(F)) { + const Bits = @Int(.unsigned, @bitSizeOf(F)); + const value: F = @bitCast(@as(Bits, @truncate(raw))); + const number_options = options.toNumber(mode, if (format == .hex_upper) .upper else .lower); + if (mode == .hex) { + try writer.printFloatHexOptions(value, number_options); + } else { + try writer.printFloat(value, number_options); + } + return; + } + } + return error.InvalidSchema; + }, + .string => { + const bytes = try cursor.string(); + if (format == .string) { + try writer.printAscii(bytes, options); + } else { + try writer.printValue("any", options, bytes, std.fmt.default_max_depth); + } + }, + .structure => { + if (depth >= std.fmt.default_max_depth) { + try skipValue(op, cursor, depth); + return writer.writeAll(".{ ... }"); + } + try writer.writeAll(".{"); + for (op.fields, 0..) |field, i| { + try writer.writeAll(if (i == 0) " " else ", "); + if (!op.is_tuple) try writer.print(".{s} = ", .{field.name}); + try renderValue(field.op, cursor, .any, options, writer, depth + 1); + } + try writer.writeAll(" }"); + }, + } + } +}; + pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptions) type { return struct { pub var loggerState: LoggerState = .{ @@ -305,7 +639,8 @@ pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptio }; // create a hash of the s: builtin sourcelocation - const sourceId = gLoggerContext.insertLogRefOrGetId(LogRef.fromSrcFmt(s, fmt), &FmtState.index); + 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)) { @@ -320,8 +655,19 @@ pub fn DeclareLogger(comptime LoggerName: []const u8, comptime opts: LoggerOptio } // stash the logs into the logger's in-memory log - // const serialized_args = gLoggerContext.serializeLogEntryArgs(sourceId, args); - // gLoggerContext.submit(loggerId, sourceId, serialized_args); + 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"); } }; } @@ -341,3 +687,92 @@ test "init logger" { 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); + 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); + var expected: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer expected.deinit(); + try expected.writer.print("[0] [0] " ++ 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", .{}); + for (0..2) |_| { + initialize(std.testing.io, 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()); + } +}