From e07e6acbe261bddfacf5e386306a120ccee93554 Mon Sep 17 00:00:00 2001 From: Daniel Samson Date: Sat, 17 Oct 2026 13:28:32 +0100 Subject: [PATCH] feat: Job JSON and Unix-socket IPC server/client (M4 part 1) Co-Authored-By: Claude Sonnet 5.5 --- AGENTS.md | 2 + src/ipc.zig | 446 +++++++++++++++++++++++++++++++++++++++++++++ src/jobjson.zig | 219 ++++++++++++++++++++++ src/jsonpretty.zig | 68 ++++++- src/root.zig | 2 + 5 files changed, 729 insertions(+), 8 deletions(-) create mode 100644 src/ipc.zig create mode 100644 src/jobjson.zig diff --git a/AGENTS.md b/AGENTS.md index 75cadf6..80db413 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -43,3 +43,5 @@ Guidance for AI coding agents working in `zag`, the Zig port of the | `src/scheduler.zig` | Per-load-level concurrency, thread per job, `killJob` | | `src/usage.zig` | `ps`/`nvidia-smi` sampling, `usage.csv`, summaries | | `src/cleanup.zig` | Automatic and manual (`zag clean`) cleanup planning | +| `src/jobjson.zig` | `Job` JSON (shared by CLI `--output=json` and IPC) | +| `src/ipc.zig` | NDJSON-over-Unix-socket server and client | diff --git a/src/ipc.zig b/src/ipc.zig new file mode 100644 index 0000000..02f9dd1 --- /dev/null +++ b/src/ipc.zig @@ -0,0 +1,446 @@ +//! Local IPC between the zag CLI and the daemon: newline-delimited JSON over a Unix socket. +//! +//! request: {"type":"get_status","payload":{...}} +//! response: {"status":"ok","payload":...} +//! {"status":"error","error":{"code":"NOT_FOUND","message":"..."}} +//! +//! A connection may carry several requests; each gets one response line. The socket is +//! created with mode 0600. +const std = @import("std"); +const Io = std.Io; +const net = Io.net; +const Allocator = std.mem.Allocator; +const jsonpretty = @import("jsonpretty.zig"); + +pub const max_request_bytes = 256 * 1024; +pub const max_response_bytes = 16 * 1024 * 1024; + +pub const ErrorCode = enum { + SERVICE_NOT_RUNNING, + CONNECTION_FAILED, + INVALID_REQUEST, + INTERNAL_ERROR, + NOT_FOUND, + INVALID_STATE, +}; + +pub const Request = struct { + type: []const u8, + /// `.null` when absent. + payload: std.json.Value = .null, + + pub fn payloadString(self: Request, key: []const u8) ?[]const u8 { + const obj = switch (self.payload) { + .object => |o| o, + else => return null, + }; + return switch (obj.get(key) orelse return null) { + .string => |s| s, + else => null, + }; + } + + pub fn payloadBool(self: Request, key: []const u8) bool { + const obj = switch (self.payload) { + .object => |o| o, + else => return false, + }; + return switch (obj.get(key) orelse return false) { + .bool => |b| b, + else => false, + }; + } + + pub fn payloadInt(self: Request, key: []const u8) ?i64 { + const obj = switch (self.payload) { + .object => |o| o, + else => return null, + }; + return switch (obj.get(key) orelse return null) { + .integer => |n| n, + else => null, + }; + } +}; + +/// What a handler fills in: write the payload through `json`, or call `fail`. +pub const Response = struct { + arena: Allocator, + json: jsonpretty.Writer, + code: ErrorCode = .INTERNAL_ERROR, + message: []const u8 = "", + + pub const Failure = error{Failure}; + + pub fn fail(self: *Response, code: ErrorCode, message: []const u8) Failure { + self.code = code; + self.message = message; + return error.Failure; + } + + pub fn failFmt(self: *Response, code: ErrorCode, comptime fmt: []const u8, args: anytype) Failure { + return self.fail(code, std.fmt.allocPrint(self.arena, fmt, args) catch "out of memory"); + } +}; + +pub const HandlerError = Response.Failure || Allocator.Error || Io.Writer.Error || anyerror; +pub const HandlerFn = *const fn (ctx: *anyopaque, req: Request, res: *Response) HandlerError!void; + +// -- server ---------------------------------------------------------------------------- + +pub const Server = struct { + gpa: Allocator, + io: Io, + socket_path: []const u8, + ctx: *anyopaque, + handler: HandlerFn, + + listener: ?net.Server = null, + thread: ?std.Thread = null, + stopping: std.atomic.Value(bool) = .init(false), + connections: std.atomic.Value(u32) = .init(0), + + pub const StartError = error{ AddressInUse, NameTooLong } || net.UnixAddress.ListenError || std.Thread.SpawnError; + + pub fn init(gpa: Allocator, io: Io, socket_path: []const u8, ctx: *anyopaque, handler: HandlerFn) Server { + return .{ .gpa = gpa, .io = io, .socket_path = socket_path, .ctx = ctx, .handler = handler }; + } + + pub fn start(self: *Server) StartError!void { + const addr = try net.UnixAddress.init(self.socket_path); + + // A live server on this path means we must not steal it; a stale file is removed. + const existing = Io.Dir.cwd().statFile(self.io, self.socket_path, .{}) catch null; + if (existing) |st| { + if (st.kind == .unix_domain_socket) { + if (addr.connect(self.io)) |stream| { + stream.close(self.io); + return error.AddressInUse; + } else |_| {} + } + Io.Dir.cwd().deleteFile(self.io, self.socket_path) catch {}; + } + + self.listener = try addr.listen(self.io, .{}); + errdefer { + self.listener.?.deinit(self.io); + self.listener = null; + } + Io.Dir.cwd().setFilePermissions(self.io, self.socket_path, @enumFromInt(0o600), .{}) catch {}; + self.stopping.store(false, .release); + self.thread = try std.Thread.spawn(.{}, acceptLoop, .{self}); + } + + /// Stops accepting, waits briefly for in-flight connections, removes the socket file. + pub fn stop(self: *Server) void { + if (self.thread == null) return; + self.stopping.store(true, .release); + // Wake the blocked accept() with a throwaway connection. + if (net.UnixAddress.init(self.socket_path)) |addr| { + if (addr.connect(self.io)) |s| s.close(self.io) else |_| {} + } else |_| {} + self.thread.?.join(); + self.thread = null; + self.listener.?.deinit(self.io); + self.listener = null; + Io.Dir.cwd().deleteFile(self.io, self.socket_path) catch {}; + + var waited: u32 = 0; + while (self.connections.load(.acquire) > 0 and waited < 2000) : (waited += 10) { + self.io.sleep(.fromMilliseconds(10), .real) catch break; + } + } + + fn acceptLoop(self: *Server) void { + while (!self.stopping.load(.acquire)) { + const stream = self.listener.?.accept(self.io) catch |err| switch (err) { + error.SocketNotListening, error.Canceled => return, + else => continue, + }; + if (self.stopping.load(.acquire)) { + stream.close(self.io); + return; + } + _ = self.connections.fetchAdd(1, .acq_rel); + const t = std.Thread.spawn(.{}, serveConnection, .{ self, stream }) catch { + stream.close(self.io); + _ = self.connections.fetchSub(1, .acq_rel); + continue; + }; + t.detach(); + } + } + + fn serveConnection(self: *Server, stream: net.Stream) void { + defer { + stream.close(self.io); + _ = self.connections.fetchSub(1, .acq_rel); + } + const rbuf = self.gpa.alloc(u8, max_request_bytes) catch return; + defer self.gpa.free(rbuf); + var wbuf: [4096]u8 = undefined; + var reader = stream.reader(self.io, rbuf); + var writer = stream.writer(self.io, &wbuf); + + while (true) { + const line = (reader.interface.takeDelimiter('\n') catch return) orelse return; + if (line.len == 0) continue; + var arena_state = std.heap.ArenaAllocator.init(self.gpa); + defer arena_state.deinit(); + const reply = self.handleLine(arena_state.allocator(), line) catch return; + writer.interface.writeAll(reply) catch return; + writer.interface.writeByte('\n') catch return; + writer.interface.flush() catch return; + } + } + + /// Builds the response line for one request line. + fn handleLine(self: *Server, arena: Allocator, line: []const u8) Allocator.Error![]const u8 { + const parsed = std.json.parseFromSliceLeaky(Request, arena, line, .{ .ignore_unknown_fields = true }) catch + return errorLine(arena, .INVALID_REQUEST, "Malformed request"); + + var payload: Io.Writer.Allocating = .init(arena); + var res: Response = .{ .arena = arena, .json = jsonpretty.Writer.initCompact(&payload.writer) }; + self.handler(self.ctx, parsed, &res) catch |err| { + if (err == error.Failure) return errorLine(arena, res.code, res.message); + return errorLine(arena, .INTERNAL_ERROR, try std.fmt.allocPrint(arena, "Failed to process request: {s}", .{@errorName(err)})); + }; + + var out: Io.Writer.Allocating = .init(arena); + out.writer.writeAll("{\"status\":\"ok\",\"payload\":") catch return error.OutOfMemory; + out.writer.writeAll(if (payload.written().len == 0) "null" else payload.written()) catch return error.OutOfMemory; + out.writer.writeByte('}') catch return error.OutOfMemory; + return out.written(); + } +}; + +fn errorLine(arena: Allocator, code: ErrorCode, message: []const u8) Allocator.Error![]const u8 { + var out: Io.Writer.Allocating = .init(arena); + var w = jsonpretty.Writer.initCompact(&out.writer); + (blk: { + w.beginObject() catch |e| break :blk e; + w.field("status", .string, "error") catch |e| break :blk e; + w.key("error") catch |e| break :blk e; + w.beginObject() catch |e| break :blk e; + w.field("code", .string, @tagName(code)) catch |e| break :blk e; + w.field("message", .string, message) catch |e| break :blk e; + w.endObject() catch |e| break :blk e; + w.endObject() catch |e| break :blk e; + }) catch return error.OutOfMemory; + return out.written(); +} + +// -- client ---------------------------------------------------------------------------- + +pub const RemoteError = struct { + code: []const u8, + message: []const u8, +}; + +pub const Reply = union(enum) { + ok: std.json.Value, + err: RemoteError, +}; + +pub const CallError = error{ ServiceNotRunning, ConnectionFailed, BadResponse } || Allocator.Error; + +/// Sends one request and waits for the reply. `payload_json` is already-encoded JSON (or null). +/// Everything in the reply is allocated from `arena`. +pub fn call(io: Io, arena: Allocator, socket_path: []const u8, request_type: []const u8, payload_json: ?[]const u8) CallError!Reply { + const addr = net.UnixAddress.init(socket_path) catch return error.ServiceNotRunning; + const stream = addr.connect(io) catch |err| switch (err) { + error.FileNotFound, error.AccessDenied, error.PermissionDenied => return error.ServiceNotRunning, + else => return error.ConnectionFailed, + }; + defer stream.close(io); + + var wbuf: [4096]u8 = undefined; + var writer = stream.writer(io, &wbuf); + var req: Io.Writer.Allocating = .init(arena); + { + var w = jsonpretty.Writer.initCompact(&req.writer); + w.beginObject() catch return error.OutOfMemory; + w.field("type", .string, request_type) catch return error.OutOfMemory; + req.writer.writeAll(",\"payload\":") catch return error.OutOfMemory; + req.writer.writeAll(payload_json orelse "null") catch return error.OutOfMemory; + req.writer.writeAll("}\n") catch return error.OutOfMemory; + } + writer.interface.writeAll(req.written()) catch return error.ConnectionFailed; + writer.interface.flush() catch return error.ConnectionFailed; + + const rbuf = try arena.alloc(u8, max_response_bytes); + var reader = stream.reader(io, rbuf); + const line = (reader.interface.takeDelimiter('\n') catch return error.ConnectionFailed) orelse return error.ConnectionFailed; + return parseReply(arena, line); +} + +pub fn parseReply(arena: Allocator, line: []const u8) CallError!Reply { + const value = std.json.parseFromSliceLeaky(std.json.Value, arena, line, .{}) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + else => return error.BadResponse, + }; + const obj = switch (value) { + .object => |o| o, + else => return error.BadResponse, + }; + const status = switch (obj.get("status") orelse return error.BadResponse) { + .string => |s| s, + else => return error.BadResponse, + }; + if (std.mem.eql(u8, status, "ok")) return .{ .ok = obj.get("payload") orelse .null }; + const e = switch (obj.get("error") orelse return error.BadResponse) { + .object => |o| o, + else => return error.BadResponse, + }; + const code = switch (e.get("code") orelse return error.BadResponse) { + .string => |s| s, + else => return error.BadResponse, + }; + const message = switch (e.get("message") orelse .null) { + .string => |s| s, + else => "", + }; + return .{ .err = .{ .code = code, .message = message } }; +} + +// -- tests ----------------------------------------------------------------------------- + +const TestCtx = struct { calls: std.atomic.Value(u32) = .init(0) }; + +fn testHandler(ctx_ptr: *anyopaque, req: Request, res: *Response) HandlerError!void { + const ctx: *TestCtx = @ptrCast(@alignCast(ctx_ptr)); + _ = ctx.calls.fetchAdd(1, .acq_rel); + if (std.mem.eql(u8, req.type, "echo")) { + try res.json.beginObject(); + try res.json.key("name"); + try res.json.optString(req.payloadString("name")); + try res.json.field("force", .boolean, req.payloadBool("force")); + try res.json.endObject(); + } else if (std.mem.eql(u8, req.type, "missing")) { + return res.failFmt(.NOT_FOUND, "Job not found: {s}", .{req.payloadString("id") orelse "?"}); + } else if (std.mem.eql(u8, req.type, "boom")) { + return error.OutOfMemory; + } else if (std.mem.eql(u8, req.type, "void")) { + return; + } else { + return res.fail(.INVALID_REQUEST, "Unknown request type"); + } +} + +fn testSocket(arena: Allocator, tmp: *std.testing.TmpDir) ![]const u8 { + return std.fmt.allocPrint(arena, ".zig-cache/tmp/{s}/zag.sock", .{tmp.sub_path}); +} + +test "request/response round trip and errors" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const path = try testSocket(arena, &tmp); + + var ctx: TestCtx = .{}; + var server = Server.init(std.testing.allocator, io, path, &ctx, testHandler); + try server.start(); + defer server.stop(); + + const ok = try call(io, arena, path, "echo", "{\"name\":\"job-1\",\"force\":true}"); + try std.testing.expectEqualStrings("job-1", ok.ok.object.get("name").?.string); + try std.testing.expect(ok.ok.object.get("force").?.bool); + + const nf = try call(io, arena, path, "missing", "{\"id\":\"job-9\"}"); + try std.testing.expectEqualStrings("NOT_FOUND", nf.err.code); + try std.testing.expectEqualStrings("Job not found: job-9", nf.err.message); + + const boom = try call(io, arena, path, "boom", null); + try std.testing.expectEqualStrings("INTERNAL_ERROR", boom.err.code); + + const unk = try call(io, arena, path, "nope", null); + try std.testing.expectEqualStrings("INVALID_REQUEST", unk.err.code); + + const empty = try call(io, arena, path, "void", null); + try std.testing.expect(empty.ok == .null); +} + +test "one connection can carry several requests; malformed input gets an error line" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const path = try testSocket(arena, &tmp); + + var ctx: TestCtx = .{}; + var server = Server.init(std.testing.allocator, io, path, &ctx, testHandler); + try server.start(); + defer server.stop(); + + const addr = try net.UnixAddress.init(path); + const stream = try addr.connect(io); + defer stream.close(io); + var wbuf: [256]u8 = undefined; + var rbuf: [4096]u8 = undefined; + var w = stream.writer(io, &wbuf); + var r = stream.reader(io, &rbuf); + + try w.interface.writeAll("{\"type\":\"echo\",\"payload\":{\"name\":\"a\"}}\nnot json\n{\"type\":\"echo\",\"payload\":{\"name\":\"b\"}}\n"); + try w.interface.flush(); + + const l1 = (try r.interface.takeDelimiter('\n')).?; + try std.testing.expectEqualStrings("{\"status\":\"ok\",\"payload\":{\"name\":\"a\",\"force\":false}}", l1); + const l2 = (try r.interface.takeDelimiter('\n')).?; + try std.testing.expect(std.mem.indexOf(u8, l2, "INVALID_REQUEST") != null); + const l3 = (try r.interface.takeDelimiter('\n')).?; + try std.testing.expectEqualStrings("{\"status\":\"ok\",\"payload\":{\"name\":\"b\",\"force\":false}}", l3); +} + +test "client reports a missing service" { + const io = std.testing.io; + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + try std.testing.expectError(error.ServiceNotRunning, call(io, arena_state.allocator(), ".zig-cache/no-such.sock", "echo", null)); +} + +test "socket is private, removed on stop, and a second server is refused" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const path = try testSocket(arena, &tmp); + + var ctx: TestCtx = .{}; + var s1 = Server.init(std.testing.allocator, io, path, &ctx, testHandler); + try s1.start(); + const st = try Io.Dir.cwd().statFile(io, path, .{}); + try std.testing.expectEqual(@as(u32, 0o600), @as(u32, @intCast(@intFromEnum(st.permissions) & 0o777))); + + var s2 = Server.init(std.testing.allocator, io, path, &ctx, testHandler); + try std.testing.expectError(error.AddressInUse, s2.start()); + + s1.stop(); + try std.testing.expectError(error.FileNotFound, Io.Dir.cwd().statFile(io, path, .{})); + try s2.start(); // path is free again + s2.stop(); +} + +test "a stale socket file is replaced" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena_state.deinit(); + const arena = arena_state.allocator(); + const path = try testSocket(arena, &tmp); + try tmp.dir.writeFile(io, .{ .sub_path = "zag.sock", .data = "stale" }); + + var ctx: TestCtx = .{}; + var s = Server.init(std.testing.allocator, io, path, &ctx, testHandler); + try s.start(); + defer s.stop(); + const reply = try call(io, arena, path, "void", null); + try std.testing.expect(reply.ok == .null); +} diff --git a/src/jobjson.zig b/src/jobjson.zig new file mode 100644 index 0000000..5ba8f9c --- /dev/null +++ b/src/jobjson.zig @@ -0,0 +1,219 @@ +//! JSON representation of a `Job`, shared by `--output=json` and the IPC protocol. +//! Field order matches barn: id, state (UPPERCASE), loadLevel, command, tag, timestamps, +//! exitCode, error, pid, heartbeat, retryCount, retryAt, terminal, running, queued. +const std = @import("std"); +const Allocator = std.mem.Allocator; +const jsonpretty = @import("jsonpretty.zig"); +const timestamp = @import("timestamp.zig"); +const state_mod = @import("state.zig"); +const LoadLevel = @import("loadlevel.zig").LoadLevel; +const job_mod = @import("job.zig"); +const Job = job_mod.Job; +const Instant = job_mod.Instant; +const ExitCode = job_mod.ExitCode; + +pub fn upperState(s: state_mod.State) []const u8 { + return switch (s) { + .queued => "QUEUED", + .running => "RUNNING", + .succeeded => "SUCCEEDED", + .failed => "FAILED", + .canceled => "CANCELED", + .killed => "KILLED", + }; +} + +pub fn writeInstant(w: *jsonpretty.Writer, t: ?Instant) !void { + const v = t orelse return w.@"null"(); + var buf: [timestamp.max_len]u8 = undefined; + try w.string(timestamp.format(&buf, v)); +} + +pub fn writeJob(w: *jsonpretty.Writer, job: Job) !void { + try w.beginObject(); + try w.field("id", .string, job.id); + try w.field("state", .string, upperState(job.state)); + try w.field("loadLevel", .string, job.load_level.upper()); + try w.key("command"); + try w.beginArray(); + for (job.command) |arg| try w.string(arg); + try w.endArray(); + try w.key("tag"); + try w.optString(job.tag); + try w.key("createdAt"); + try writeInstant(w, job.created_at); + try w.key("startedAt"); + try writeInstant(w, job.started_at); + try w.key("finishedAt"); + try writeInstant(w, job.finished_at); + try w.key("exitCode"); + if (job.exit_code) |c| switch (c) { + .code => |n| try w.int(n), + .symbol => |s| try w.string(s), + } else try w.@"null"(); + try w.key("error"); + try w.optString(job.err); + try w.key("pid"); + if (job.pid) |p| try w.int(p) else try w.@"null"(); + try w.key("heartbeat"); + try writeInstant(w, job.heartbeat); + try w.field("retryCount", .int, job.retry_count); + try w.key("retryAt"); + try writeInstant(w, job.retry_at); + try w.field("terminal", .boolean, job.isTerminal()); + try w.field("running", .boolean, job.isRunning()); + try w.field("queued", .boolean, job.isQueued()); + try w.endObject(); +} + +pub fn writeJobs(w: *jsonpretty.Writer, jobs: []const Job) !void { + try w.beginArray(); + for (jobs) |j| try writeJob(w, j); + try w.endArray(); +} + +const RawJob = struct { + id: []const u8, + state: []const u8, + loadLevel: ?[]const u8 = null, + command: []const []const u8, + tag: ?[]const u8 = null, + createdAt: []const u8, + startedAt: ?[]const u8 = null, + finishedAt: ?[]const u8 = null, + exitCode: ?std.json.Value = null, + @"error": ?[]const u8 = null, + pid: ?i64 = null, + heartbeat: ?[]const u8 = null, + retryCount: u32 = 0, + retryAt: ?[]const u8 = null, +}; + +pub const ParseError = error{InvalidJob} || Allocator.Error; + +fn optInstant(text: ?[]const u8) ParseError!?Instant { + const t = text orelse return null; + return timestamp.parse(t) catch return error.InvalidJob; +} + +/// Converts a parsed JSON value (as produced by `writeJob`) back into a `Job`. +pub fn jobFromValue(arena: Allocator, value: std.json.Value) ParseError!Job { + const raw = std.json.parseFromValueLeaky(RawJob, arena, value, .{ .ignore_unknown_fields = true }) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + else => return error.InvalidJob, + }; + return .{ + .id = raw.id, + .state = state_mod.State.parse(raw.state) orelse return error.InvalidJob, + .command = raw.command, + .tag = raw.tag, + .created_at = (try optInstant(raw.createdAt)).?, + .started_at = try optInstant(raw.startedAt), + .finished_at = try optInstant(raw.finishedAt), + .exit_code = if (raw.exitCode) |v| switch (v) { + .integer => |n| .{ .code = std.math.cast(i32, n) orelse return error.InvalidJob }, + .string => |s| .{ .symbol = s }, + .null => null, + else => return error.InvalidJob, + } else null, + .err = raw.@"error", + .pid = raw.pid, + .heartbeat = try optInstant(raw.heartbeat), + .retry_count = raw.retryCount, + .retry_at = try optInstant(raw.retryAt), + .load_level = if (raw.loadLevel) |l| LoadLevel.parse(l) orelse return error.InvalidJob else .medium, + }; +} + +pub fn jobsFromValue(arena: Allocator, value: std.json.Value) ParseError![]Job { + const arr = switch (value) { + .array => |a| a.items, + else => return error.InvalidJob, + }; + const out = try arena.alloc(Job, arr.len); + for (arr, out) |v, *slot| slot.* = try jobFromValue(arena, v); + return out; +} + +fn sampleJob() Job { + return .{ + .id = "job-6d368040", + .state = .succeeded, + .command = &.{ "echo", "Hello World" }, + .created_at = 1_769_046_526 * std.time.ns_per_s + 739_979_000, + .started_at = 1_769_046_527 * std.time.ns_per_s + 161_895_000, + .finished_at = 1_769_046_527 * std.time.ns_per_s + 184_605_000, + .exit_code = .{ .code = 0 }, + .pid = 17486, + .heartbeat = 1_769_046_527 * std.time.ns_per_s + 161_895_000, + .load_level = .medium, + }; +} + +test "job JSON matches barn's field layout" { + var aw: std.Io.Writer.Allocating = .init(std.testing.allocator); + defer aw.deinit(); + var w = jsonpretty.Writer.init(&aw.writer); + try writeJob(&w, sampleJob()); + try std.testing.expectEqualStrings( + \\{ + \\ "id" : "job-6d368040", + \\ "state" : "SUCCEEDED", + \\ "loadLevel" : "MEDIUM", + \\ "command" : [ "echo", "Hello World" ], + \\ "tag" : null, + \\ "createdAt" : "2026-01-22T01:48:46.739979Z", + \\ "startedAt" : "2026-01-22T01:48:47.161895Z", + \\ "finishedAt" : "2026-01-22T01:48:47.184605Z", + \\ "exitCode" : 0, + \\ "error" : null, + \\ "pid" : 17486, + \\ "heartbeat" : "2026-01-22T01:48:47.161895Z", + \\ "retryCount" : 0, + \\ "retryAt" : null, + \\ "terminal" : true, + \\ "running" : false, + \\ "queued" : false + \\} + , aw.written()); +} + +test "jobs round-trip through compact JSON" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var failed = sampleJob(); + failed.state = .failed; + failed.exit_code = .{ .symbol = "start_failed" }; + failed.err = "boom \"quoted\""; + failed.tag = "t"; + failed.retry_count = 2; + failed.retry_at = failed.created_at + std.time.ns_per_s; + failed.load_level = .low; + const jobs = [_]Job{ sampleJob(), failed }; + + var aw: std.Io.Writer.Allocating = .init(a); + var w = jsonpretty.Writer.initCompact(&aw.writer); + try writeJobs(&w, &jobs); + + const value = try std.json.parseFromSliceLeaky(std.json.Value, a, aw.written(), .{}); + const back = try jobsFromValue(a, value); + try std.testing.expectEqual(@as(usize, 2), back.len); + try std.testing.expectEqualStrings("job-6d368040", back[0].id); + try std.testing.expectEqual(@as(i32, 0), back[0].exit_code.?.code); + try std.testing.expectEqual(jobs[0].created_at, back[0].created_at); + try std.testing.expectEqual(state_mod.State.failed, back[1].state); + try std.testing.expectEqualStrings("start_failed", back[1].exit_code.?.symbol); + try std.testing.expectEqualStrings("boom \"quoted\"", back[1].err.?); + try std.testing.expectEqual(@as(u32, 2), back[1].retry_count); + try std.testing.expectEqual(LoadLevel.low, back[1].load_level); + try std.testing.expectEqual(failed.retry_at.?, back[1].retry_at.?); +} + +test "invalid jobs are rejected" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const v = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"id\":\"x\"}", .{}); + try std.testing.expectError(error.InvalidJob, jobFromValue(a, v)); +} diff --git a/src/jsonpretty.zig b/src/jsonpretty.zig index b873603..b09c8c0 100644 --- a/src/jsonpretty.zig +++ b/src/jsonpretty.zig @@ -14,6 +14,8 @@ //! Objects put one member per line with two-space indent and ` : ` between key and value. //! Arrays are always inline (`[ a, b ]`), and objects inside an array indent relative to the //! enclosing object, not the array. +//! +//! `Writer.initCompact` emits minified JSON (`{"a":1,"b":[1,2]}`) for line-oriented IPC. const std = @import("std"); const Io = std.Io; @@ -31,6 +33,7 @@ pub const Writer = struct { after_key: bool = false, /// Number of enclosing objects, which determines indentation. object_level: usize = 0, + compact: bool = false, pub const Error = Io.Writer.Error; @@ -38,6 +41,10 @@ pub const Writer = struct { return .{ .out = out }; } + pub fn initCompact(out: *Io.Writer) Writer { + return .{ .out = out, .compact = true }; + } + pub fn beginObject(self: *Writer) Error!void { try self.beforeValue(); self.push(.{ .is_object = true }); @@ -47,7 +54,9 @@ pub const Writer = struct { pub fn endObject(self: *Writer) Error!void { const f = self.pop(); std.debug.assert(f.is_object); - if (f.opened) { + if (self.compact) { + try self.out.writeAll(if (f.opened) "}" else "{}"); + } else if (f.opened) { try self.out.writeByte('\n'); try self.indent(self.object_level - 1); try self.out.writeByte('}'); @@ -65,17 +74,28 @@ pub const Writer = struct { pub fn endArray(self: *Writer) Error!void { const f = self.pop(); std.debug.assert(!f.is_object); - try self.out.writeAll(if (f.opened) " ]" else "[ ]"); + if (self.compact) { + try self.out.writeAll(if (f.opened) "]" else "[]"); + } else { + try self.out.writeAll(if (f.opened) " ]" else "[ ]"); + } } pub fn key(self: *Writer, name: []const u8) Error!void { const f = &self.stack[self.depth - 1]; std.debug.assert(f.is_object and !self.after_key); - try self.out.writeAll(if (f.opened) ",\n" else "{\n"); - f.opened = true; - try self.indent(self.object_level); - try std.json.Stringify.encodeJsonString(name, .{}, self.out); - try self.out.writeAll(" : "); + if (self.compact) { + try self.out.writeAll(if (f.opened) "," else "{"); + f.opened = true; + try std.json.Stringify.encodeJsonString(name, .{}, self.out); + try self.out.writeByte(':'); + } else { + try self.out.writeAll(if (f.opened) ",\n" else "{\n"); + f.opened = true; + try self.indent(self.object_level); + try std.json.Stringify.encodeJsonString(name, .{}, self.out); + try self.out.writeAll(" : "); + } self.after_key = true; } @@ -131,7 +151,11 @@ pub const Writer = struct { return; } std.debug.assert(!f.is_object); // object members need a key first - try self.out.writeAll(if (f.opened) ", " else "[ "); + if (self.compact) { + try self.out.writeAll(if (f.opened) "," else "["); + } else { + try self.out.writeAll(if (f.opened) ", " else "[ "); + } f.opened = true; } @@ -271,3 +295,31 @@ test "top-level empty object" { defer std.testing.allocator.free(out); try std.testing.expectEqualStrings("{ }", out); } + +test "compact style has no whitespace" { + var aw: Io.Writer.Allocating = .init(std.testing.allocator); + defer aw.deinit(); + var w = Writer.initCompact(&aw.writer); + try w.beginObject(); + try w.field("status", .string, "ok"); + try w.key("payload"); + try w.beginObject(); + try w.key("jobs"); + try w.beginArray(); + try w.beginObject(); + try w.field("id", .int, 1); + try w.endObject(); + try w.beginObject(); + try w.endObject(); + try w.endArray(); + try w.key("empty"); + try w.beginArray(); + try w.endArray(); + try w.key("tag"); + try w.@"null"(); + try w.endObject(); + try w.endObject(); + try std.testing.expectEqualStrings( + \\{"status":"ok","payload":{"jobs":[{"id":1},{}],"empty":[],"tag":null}} + , aw.written()); +} diff --git a/src/root.zig b/src/root.zig index 87571e9..5a52595 100644 --- a/src/root.zig +++ b/src/root.zig @@ -21,6 +21,8 @@ pub const recovery = @import("recovery.zig"); pub const scheduler = @import("scheduler.zig"); pub const usage = @import("usage.zig"); pub const cleanup = @import("cleanup.zig"); +pub const jobjson = @import("jobjson.zig"); +pub const ipc = @import("ipc.zig"); test { @import("std").testing.refAllDecls(@This());