diff --git a/AGENTS.md b/AGENTS.md index 39d2e3f..5908d48 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,3 +28,8 @@ Guidance for AI coding agents working in `zag`, the Zig port of the | `src/fsutil.zig` | Atomic writes, trimmed reads, advisory `FileLock` | | `src/jsonpretty.zig` | Streaming JSON writer matching Jackson `INDENT_OUTPUT` layout | | `src/toml.zig` | Parser for barn's TOML subset (`[section]`, `key = value`, arrays) | +| `src/loadlevel.zig` | `high`/`medium`/`low` load levels | +| `src/job.zig` | `Job`, `Manifest`, `ExitCode` types | +| `src/dirs.zig` | On-disk layout under the base dir | +| `src/statefiles.zig` | One-value-per-file job state (atomic) | +| `src/repository.zig` | Job create/find/transition/retry persistence, `manifest.json` I/O | diff --git a/src/dirs.zig b/src/dirs.zig new file mode 100644 index 0000000..674abfa --- /dev/null +++ b/src/dirs.zig @@ -0,0 +1,100 @@ +//! The on-disk layout under the base directory (`/tmp/zag` by default): +//! +//! /jobs//{manifest.json, state, ..., work/{input,output}, logs/} +//! /locks/scheduler.lock +//! /logs/zag.log +//! /zag.pid, /zag.sock +const std = @import("std"); +const Io = std.Io; +const Dir = Io.Dir; + +pub const jobs_dir = "jobs"; +pub const locks_dir = "locks"; +pub const logs_dir = "logs"; +pub const work_dir = "work"; +pub const input_dir = "input"; +pub const output_dir = "output"; +pub const scheduler_lock = "locks/scheduler.lock"; +pub const daemon_log = "logs/zag.log"; +pub const pid_file = "zag.pid"; +pub const socket_file = "zag.sock"; + +pub const Dirs = struct { + /// Open handle on the base directory. + base: Dir, + /// Path of the base directory as given (used for display and socket paths). + base_path: []const u8, + + pub fn open(io: Io, base_path: []const u8) !Dirs { + const cwd = Dir.cwd(); + try cwd.createDirPath(io, base_path); + var dirs: Dirs = .{ + .base = try cwd.openDir(io, base_path, .{}), + .base_path = base_path, + }; + try dirs.initialize(io); + return dirs; + } + + pub fn close(self: *Dirs, io: Io) void { + self.base.close(io); + } + + /// Creates `jobs/`, `locks/` and `logs/` if missing. + pub fn initialize(self: *Dirs, io: Io) !void { + try self.base.createDirPath(io, jobs_dir); + try self.base.createDirPath(io, locks_dir); + try self.base.createDirPath(io, logs_dir); + } + + /// Creates `jobs//{work/input,work/output,logs}`. + pub fn createJobDirs(self: *Dirs, io: Io, id: []const u8) !void { + var buf: [256]u8 = undefined; + for ([_][]const u8{ "work/input", "work/output", "logs" }) |sub| { + try self.base.createDirPath(io, try std.fmt.bufPrint(&buf, "{s}/{s}/{s}", .{ jobs_dir, id, sub })); + } + } + + pub fn jobExists(self: *Dirs, io: Io, id: []const u8) bool { + var buf: [256]u8 = undefined; + const p = std.fmt.bufPrint(&buf, "{s}/{s}", .{ jobs_dir, id }) catch return false; + _ = self.base.statFile(io, p, .{}) catch return false; + return true; + } + + pub fn openJob(self: *Dirs, io: Io, id: []const u8) !Dir { + var buf: [256]u8 = undefined; + return self.base.openDir(io, try std.fmt.bufPrint(&buf, "{s}/{s}", .{ jobs_dir, id }), .{}); + } + + pub fn deleteJob(self: *Dirs, io: Io, id: []const u8) !void { + var buf: [256]u8 = undefined; + try self.base.deleteTree(io, try std.fmt.bufPrint(&buf, "{s}/{s}", .{ jobs_dir, id })); + } + + /// Absolute-or-relative path strings for display, allocated from `arena`. + pub fn jobPath(self: Dirs, arena: std.mem.Allocator, id: []const u8, sub: []const u8) ![]u8 { + if (sub.len == 0) return std.fmt.allocPrint(arena, "{s}/{s}/{s}", .{ self.base_path, jobs_dir, id }); + return std.fmt.allocPrint(arena, "{s}/{s}/{s}/{s}", .{ self.base_path, jobs_dir, id, sub }); + } +}; + +test "open creates the skeleton and job dirs" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const base = try std.fmt.allocPrint(arena.allocator(), ".zig-cache/tmp/{s}/zag", .{tmp.sub_path}); + + var d = try Dirs.open(io, base); + defer d.close(io); + try std.testing.expect(!d.jobExists(io, "job-aaaaaaaa")); + try d.createJobDirs(io, "job-aaaaaaaa"); + try std.testing.expect(d.jobExists(io, "job-aaaaaaaa")); + _ = try d.base.statFile(io, "jobs/job-aaaaaaaa/work/input", .{}); + _ = try d.base.statFile(io, "jobs/job-aaaaaaaa/logs", .{}); + _ = try d.base.statFile(io, "locks", .{}); + try d.deleteJob(io, "job-aaaaaaaa"); + try std.testing.expect(!d.jobExists(io, "job-aaaaaaaa")); +} diff --git a/src/fsutil.zig b/src/fsutil.zig index 8ad775f..df088b5 100644 --- a/src/fsutil.zig +++ b/src/fsutil.zig @@ -28,6 +28,18 @@ pub fn readTrimmed(io: Io, gpa: Allocator, dir: Dir, sub_path: []const u8) !?[]u return try gpa.dupe(u8, std.mem.trim(u8, raw, &std.ascii.whitespace)); } +/// Reads a small file into `buf` and returns it trimmed (a slice of `buf`), or null if the file +/// does not exist. Content longer than `buf` is truncated. +pub fn readTrimmedBuf(io: Io, dir: Dir, sub_path: []const u8, buf: []u8) !?[]const u8 { + var file = dir.openFile(io, sub_path, .{}) catch |err| switch (err) { + error.FileNotFound => return null, + else => |e| return e, + }; + defer file.close(io); + const n = try file.readPositionalAll(io, buf, 0); + return std.mem.trim(u8, buf[0..n], &std.ascii.whitespace); +} + /// Deletes `sub_path`; a file that is already gone is not an error. pub fn deleteIfExists(io: Io, dir: Dir, sub_path: []const u8) !void { dir.deleteFile(io, sub_path) catch |err| switch (err) { diff --git a/src/job.zig b/src/job.zig new file mode 100644 index 0000000..fcf99b1 --- /dev/null +++ b/src/job.zig @@ -0,0 +1,86 @@ +//! Job and manifest data types. Timestamps are nanoseconds since the Unix epoch (`Instant`). +const std = @import("std"); +const State = @import("state.zig").State; +const LoadLevel = @import("loadlevel.zig").LoadLevel; + +pub const Instant = i128; + +/// A process exit status, or a symbolic code such as `start_failed` or `interrupted`. +pub const ExitCode = union(enum) { + code: i32, + symbol: []const u8, + + pub fn parse(text: []const u8) ExitCode { + if (std.fmt.parseInt(i32, text, 10)) |n| return .{ .code = n } else |_| {} + return .{ .symbol = text }; + } +}; + +pub const Job = struct { + id: []const u8, + state: State, + command: []const []const u8, + tag: ?[]const u8 = null, + created_at: Instant, + started_at: ?Instant = null, + finished_at: ?Instant = null, + exit_code: ?ExitCode = null, + err: ?[]const u8 = null, + pid: ?i64 = null, + heartbeat: ?Instant = null, + retry_count: u32 = 0, + retry_at: ?Instant = null, + load_level: LoadLevel = .medium, + + pub fn isTerminal(self: Job) bool { + return self.state.isTerminal(); + } + + pub fn isRunning(self: Job) bool { + return self.state == .running; + } + + pub fn isQueued(self: Job) bool { + return self.state == .queued; + } +}; + +/// Immutable record written once to `manifest.json` when a job is created. +pub const Manifest = struct { + id: []const u8, + command: []const []const u8, + tag: ?[]const u8 = null, + created_at: Instant, + max_retries: u32 = 0, + retry_delay_seconds: u32 = 30, + retry_backoff_multiplier: f64 = 2.0, + load_level: LoadLevel = .medium, + + pub const ValidationError = error{ BlankId, EmptyCommand, BadBackoff }; + + pub fn validate(self: Manifest) ValidationError!void { + if (std.mem.trim(u8, self.id, &std.ascii.whitespace).len == 0) return error.BlankId; + if (self.command.len == 0) return error.EmptyCommand; + if (self.retry_backoff_multiplier < 1.0) return error.BadBackoff; + } +}; + +test "ExitCode.parse distinguishes numbers from symbols" { + try std.testing.expectEqual(@as(i32, 0), ExitCode.parse("0").code); + try std.testing.expectEqual(@as(i32, -1), ExitCode.parse("-1").code); + try std.testing.expectEqualStrings("start_failed", ExitCode.parse("start_failed").symbol); +} + +test "manifest validation" { + const ok: Manifest = .{ .id = "job-1", .command = &.{"echo"}, .created_at = 0 }; + try ok.validate(); + var bad = ok; + bad.command = &.{}; + try std.testing.expectError(error.EmptyCommand, bad.validate()); + bad = ok; + bad.id = " "; + try std.testing.expectError(error.BlankId, bad.validate()); + bad = ok; + bad.retry_backoff_multiplier = 0.5; + try std.testing.expectError(error.BadBackoff, bad.validate()); +} diff --git a/src/loadlevel.zig b/src/loadlevel.zig new file mode 100644 index 0000000..6305c68 --- /dev/null +++ b/src/loadlevel.zig @@ -0,0 +1,56 @@ +//! Load levels cap how many jobs of each weight run at once. +const std = @import("std"); + +pub const LoadLevel = enum { + high, + medium, + low, + + pub const default: LoadLevel = .medium; + + pub fn defaultMaxJobs(self: LoadLevel) u32 { + return switch (self) { + .high => 2, + .medium => 8, + .low => 32, + }; + } + + pub fn lower(self: LoadLevel) []const u8 { + return @tagName(self); + } + + /// Uppercase form used in JSON (`HIGH`, `MEDIUM`, `LOW`) and manifests. + pub fn upper(self: LoadLevel) []const u8 { + return switch (self) { + .high => "HIGH", + .medium => "MEDIUM", + .low => "LOW", + }; + } + + /// Case-insensitive; surrounding whitespace is ignored. + pub fn parse(text: []const u8) ?LoadLevel { + const t = std.mem.trim(u8, text, &std.ascii.whitespace); + inline for (@typeInfo(LoadLevel).@"enum".fields) |f| { + if (std.ascii.eqlIgnoreCase(t, f.name)) return @field(LoadLevel, f.name); + } + return null; + } +}; + +test "defaults and names" { + try std.testing.expectEqual(LoadLevel.medium, LoadLevel.default); + try std.testing.expectEqual(@as(u32, 2), LoadLevel.high.defaultMaxJobs()); + try std.testing.expectEqual(@as(u32, 8), LoadLevel.medium.defaultMaxJobs()); + try std.testing.expectEqual(@as(u32, 32), LoadLevel.low.defaultMaxJobs()); + try std.testing.expectEqualStrings("HIGH", LoadLevel.high.upper()); + try std.testing.expectEqualStrings("low", LoadLevel.low.lower()); +} + +test "parse is case-insensitive and trims" { + try std.testing.expectEqual(LoadLevel.high, LoadLevel.parse(" High ").?); + try std.testing.expectEqual(LoadLevel.low, LoadLevel.parse("LOW").?); + try std.testing.expect(LoadLevel.parse("extreme") == null); + try std.testing.expect(LoadLevel.parse("") == null); +} diff --git a/src/repository.zig b/src/repository.zig new file mode 100644 index 0000000..1fc503a --- /dev/null +++ b/src/repository.zig @@ -0,0 +1,517 @@ +//! Job persistence on top of `Dirs` and `StateFiles`. Port of barn's `JobRepository`. +//! +//! Functions that return jobs or manifests take an `arena`: everything they return +//! (strings, slices) is allocated from it and freed when the caller resets the arena. +const std = @import("std"); +const Io = std.Io; +const Allocator = std.mem.Allocator; +const Dirs = @import("dirs.zig").Dirs; +const dirs_mod = @import("dirs.zig"); +const StateFiles = @import("statefiles.zig").StateFiles; +const State = @import("state.zig").State; +const LoadLevel = @import("loadlevel.zig").LoadLevel; +const job_mod = @import("job.zig"); +const Job = job_mod.Job; +const Manifest = job_mod.Manifest; +const ExitCode = job_mod.ExitCode; +const Instant = job_mod.Instant; +const jobid = @import("jobid.zig"); +const timestamp = @import("timestamp.zig"); +const fsutil = @import("fsutil.zig"); +const jsonpretty = @import("jsonpretty.zig"); + +pub const manifest_file = "manifest.json"; + +pub const Error = error{ InvalidTransition, JobNotFound, InvalidManifest }; + +pub const CreateOptions = struct { + tag: ?[]const u8 = null, + load_level: LoadLevel = .medium, + max_retries: u32 = 3, + retry_delay_seconds: u32 = 30, + retry_backoff_multiplier: f64 = 2.0, +}; + +pub const Repository = struct { + io: Io, + dirs: *Dirs, + + pub fn init(io: Io, dirs: *Dirs) Repository { + return .{ .io = io, .dirs = dirs }; + } + + fn stateFiles(self: Repository, id: []const u8) !struct { dir: Io.Dir, sf: StateFiles } { + const dir = self.dirs.openJob(self.io, id) catch |err| switch (err) { + error.FileNotFound => return error.JobNotFound, + else => |e| return e, + }; + return .{ .dir = dir, .sf = StateFiles.init(self.io, dir) }; + } + + // -- create --------------------------------------------------------------------- + + /// Creates a new queued job: directories, `manifest.json`, `state`, `created_at`, + /// `tag` (if any) and `retry_count`. + pub fn create(self: Repository, arena: Allocator, command: []const []const u8, opts: CreateOptions) !Job { + var id = jobid.generate(self.io); + while (self.dirs.jobExists(self.io, &id)) id = jobid.generate(self.io); + const id_str = try arena.dupe(u8, &id); + + const manifest: Manifest = .{ + .id = id_str, + .command = command, + .tag = opts.tag, + .created_at = timestamp.now(self.io), + .max_retries = opts.max_retries, + .retry_delay_seconds = opts.retry_delay_seconds, + .retry_backoff_multiplier = opts.retry_backoff_multiplier, + .load_level = opts.load_level, + }; + try manifest.validate(); + + try self.dirs.createJobDirs(self.io, id_str); + var job_dir = try self.dirs.openJob(self.io, id_str); + defer job_dir.close(self.io); + + var aw: Io.Writer.Allocating = .init(arena); + try writeManifestJson(&aw.writer, manifest); + try fsutil.writeAtomic(self.io, job_dir, manifest_file, aw.written()); + + const sf = StateFiles.init(self.io, job_dir); + try sf.writeState(.queued); + try sf.writeCreatedAt(manifest.created_at); + if (opts.tag) |t| try sf.writeTag(t); + try sf.writeRetryCount(0); + + return .{ + .id = id_str, + .state = .queued, + .command = command, + .tag = opts.tag, + .created_at = manifest.created_at, + .load_level = opts.load_level, + }; + } + + // -- read ----------------------------------------------------------------------- + + pub fn findById(self: Repository, arena: Allocator, id: []const u8) !?Job { + if (!self.dirs.jobExists(self.io, id)) return null; + return try self.loadJob(arena, id); + } + + /// All jobs found under `jobs/`. Unreadable job directories are skipped. + pub fn findAll(self: Repository, arena: Allocator) ![]Job { + var jobs_dir = self.dirs.base.openDir(self.io, dirs_mod.jobs_dir, .{ .iterate = true }) catch |err| switch (err) { + error.FileNotFound => return &.{}, + else => |e| return e, + }; + defer jobs_dir.close(self.io); + + var list: std.ArrayList(Job) = .empty; + var it = jobs_dir.iterate(); + while (try it.next(self.io)) |entry| { + if (entry.kind != .directory) continue; + const j = self.loadJob(arena, entry.name) catch continue; + try list.append(arena, j); + } + return list.toOwnedSlice(arena); + } + + pub fn findByState(self: Repository, arena: Allocator, state: State) ![]Job { + const all = try self.findAll(arena); + var list: std.ArrayList(Job) = .empty; + for (all) |j| if (j.state == state) try list.append(arena, j); + return list.toOwnedSlice(arena); + } + + pub fn loadManifest(self: Repository, arena: Allocator, id: []const u8) !Manifest { + var job_dir = self.dirs.openJob(self.io, id) catch |err| switch (err) { + error.FileNotFound => return error.JobNotFound, + else => |e| return e, + }; + defer job_dir.close(self.io); + const text = try job_dir.readFileAlloc(self.io, manifest_file, arena, .limited(1 << 20)); + return parseManifestJson(arena, text); + } + + fn loadJob(self: Repository, arena: Allocator, id: []const u8) !Job { + const manifest = try self.loadManifest(arena, id); + var job_dir = try self.dirs.openJob(self.io, id); + defer job_dir.close(self.io); + const sf = StateFiles.init(self.io, job_dir); + + return .{ + .id = manifest.id, + .state = (try sf.readState()) orelse .queued, + .command = manifest.command, + .tag = try sf.readTag(arena), + .created_at = (try sf.readCreatedAt()) orelse manifest.created_at, + .started_at = try sf.readStartedAt(), + .finished_at = try sf.readFinishedAt(), + .exit_code = try sf.readExitCode(arena), + .err = try sf.readError(arena), + .pid = try sf.readPid(), + .heartbeat = try sf.readHeartbeat(), + .retry_count = (try sf.readRetryCount()) orelse 0, + .retry_at = try sf.readRetryAt(), + .load_level = manifest.load_level, + }; + } + + // -- transitions ---------------------------------------------------------------- + + /// Validates the transition against the current state (when one is recorded). + pub fn updateState(self: Repository, id: []const u8, next: State) !void { + var h = try self.stateFiles(id); + defer h.dir.close(self.io); + try self.transition(h.sf, next); + } + + fn transition(self: Repository, sf: StateFiles, next: State) !void { + _ = self; + if (try sf.readState()) |cur| { + if (!cur.canTransitionTo(next)) return error.InvalidTransition; + } + try sf.writeState(next); + } + + pub fn markStarted(self: Repository, id: []const u8, pid: i64) !void { + var h = try self.stateFiles(id); + defer h.dir.close(self.io); + const now = timestamp.now(self.io); + try self.transition(h.sf, .running); + try h.sf.writeStartedAt(now); + try h.sf.writePid(pid); + try h.sf.writeHeartbeat(now); + } + + pub fn updateHeartbeat(self: Repository, id: []const u8, at: Instant) !void { + var h = try self.stateFiles(id); + defer h.dir.close(self.io); + try h.sf.writeHeartbeat(at); + } + + /// Exit code 0 -> succeeded, anything else -> failed. + pub fn markCompleted(self: Repository, id: []const u8, exit_code: i32, err: ?[]const u8) !void { + var h = try self.stateFiles(id); + defer h.dir.close(self.io); + try self.transition(h.sf, if (exit_code == 0) .succeeded else .failed); + try h.sf.writeFinishedAt(timestamp.now(self.io)); + try h.sf.writeExitCode(.{ .code = exit_code }); + if (err) |e| try h.sf.writeError(e); + } + + /// Fails a job with a symbolic exit code such as `start_failed`. + pub fn markFailed(self: Repository, id: []const u8, symbol: []const u8, err: ?[]const u8) !void { + var h = try self.stateFiles(id); + defer h.dir.close(self.io); + try self.transition(h.sf, .failed); + try h.sf.writeFinishedAt(timestamp.now(self.io)); + try h.sf.writeExitCode(.{ .symbol = symbol }); + if (err) |e| try h.sf.writeError(e); + } + + pub fn markKilled(self: Repository, id: []const u8, err: ?[]const u8) !void { + var h = try self.stateFiles(id); + defer h.dir.close(self.io); + try self.transition(h.sf, .killed); + try h.sf.writeFinishedAt(timestamp.now(self.io)); + if (err) |e| try h.sf.writeError(e); + } + + pub fn markCanceled(self: Repository, id: []const u8) !void { + var h = try self.stateFiles(id); + defer h.dir.close(self.io); + try self.transition(h.sf, .canceled); + try h.sf.writeFinishedAt(timestamp.now(self.io)); + try h.sf.writeError("Job was canceled"); + } + + /// Records a history line, bumps `retry_count`, sets `retry_at`, requeues the job and + /// clears runtime state (`started_at`, `heartbeat`, `finished_at`). + pub fn scheduleRetry( + self: Repository, + gpa: Allocator, + id: []const u8, + retry_at: Instant, + exit_code: ?i32, + err: ?[]const u8, + ) !void { + var h = try self.stateFiles(id); + defer h.dir.close(self.io); + const count = (try h.sf.readRetryCount()) orelse 0; + + const entry = try formatRetryHistoryEntry(gpa, timestamp.now(self.io), count + 1, exit_code, err); + defer gpa.free(entry); + try h.sf.appendRetryHistory(gpa, entry); + + try h.sf.writeRetryCount(count + 1); + try h.sf.writeRetryAt(retry_at); + try self.transition(h.sf, .queued); + try h.sf.writeStartedAt(null); + try h.sf.writeHeartbeat(null); + try h.sf.writeFinishedAt(null); + } + + pub fn delete(self: Repository, id: []const u8) !void { + try self.dirs.deleteJob(self.io, id); + } +}; + +/// `ISO|attempt=N[|exit_code=C][|error=...]`; newlines in the error become spaces and `|` becomes `;`. +fn formatRetryHistoryEntry(gpa: Allocator, now: Instant, attempt: u32, exit_code: ?i32, err: ?[]const u8) ![]u8 { + var aw: Io.Writer.Allocating = .init(gpa); + errdefer aw.deinit(); + var tbuf: [timestamp.max_len]u8 = undefined; + try aw.writer.print("{s}|attempt={d}", .{ timestamp.format(&tbuf, now), attempt }); + if (exit_code) |c| try aw.writer.print("|exit_code={d}", .{c}); + if (err) |e| { + try aw.writer.writeAll("|error="); + for (e) |ch| try aw.writer.writeByte(switch (ch) { + '\n' => ' ', + '|' => ';', + else => ch, + }); + } + return aw.toOwnedSlice(); +} + +// -- manifest JSON (Jackson-compatible layout and field names) ------------------------- + +pub fn writeManifestJson(out: *Io.Writer, m: Manifest) !void { + var w = jsonpretty.Writer.init(out); + var tbuf: [timestamp.max_len]u8 = undefined; + try w.beginObject(); + try w.field("id", .string, m.id); + try w.key("command"); + try w.beginArray(); + for (m.command) |arg| try w.string(arg); + try w.endArray(); + try w.key("tag"); + try w.optString(m.tag); + try w.field("createdAt", .string, timestamp.format(&tbuf, m.created_at)); + try w.field("maxRetries", .int, m.max_retries); + try w.field("retryDelaySeconds", .int, m.retry_delay_seconds); + try w.field("retryBackoffMultiplier", .float, m.retry_backoff_multiplier); + try w.field("loadLevel", .string, m.load_level.upper()); + try w.endObject(); +} + +const RawManifest = struct { + id: []const u8, + command: []const []const u8, + tag: ?[]const u8 = null, + createdAt: []const u8, + maxRetries: u32 = 0, + retryDelaySeconds: u32 = 30, + retryBackoffMultiplier: f64 = 2.0, + loadLevel: ?[]const u8 = null, +}; + +/// Parses a barn- or zag-written `manifest.json`. A missing `loadLevel` defaults to MEDIUM. +pub fn parseManifestJson(arena: Allocator, text: []const u8) !Manifest { + const raw = std.json.parseFromSliceLeaky(RawManifest, arena, text, .{ .ignore_unknown_fields = true }) catch + return error.InvalidManifest; + const m: Manifest = .{ + .id = raw.id, + .command = raw.command, + .tag = raw.tag, + .created_at = timestamp.parse(raw.createdAt) catch return error.InvalidManifest, + .max_retries = raw.maxRetries, + .retry_delay_seconds = raw.retryDelaySeconds, + .retry_backoff_multiplier = raw.retryBackoffMultiplier, + .load_level = if (raw.loadLevel) |l| LoadLevel.parse(l) orelse return error.InvalidManifest else .medium, + }; + m.validate() catch return error.InvalidManifest; + return m; +} + +// -- tests ----------------------------------------------------------------------------- + +const TestEnv = struct { + tmp: std.testing.TmpDir, + arena: std.heap.ArenaAllocator, + dirs: Dirs, + + fn init() !*TestEnv { + const self = try std.testing.allocator.create(TestEnv); + self.tmp = std.testing.tmpDir(.{}); + self.arena = std.heap.ArenaAllocator.init(std.testing.allocator); + const base = try std.fmt.allocPrint(self.arena.allocator(), ".zig-cache/tmp/{s}/zag", .{self.tmp.sub_path}); + self.dirs = try Dirs.open(std.testing.io, base); + return self; + } + + fn deinit(self: *TestEnv) void { + self.dirs.close(std.testing.io); + self.arena.deinit(); + self.tmp.cleanup(); + std.testing.allocator.destroy(self); + } + + fn repo(self: *TestEnv) Repository { + return Repository.init(std.testing.io, &self.dirs); + } +}; + +test "manifest JSON matches barn's layout and round-trips" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const m: Manifest = .{ + .id = "job-6d368040", + .command = &.{ "echo", "Hello World" }, + .created_at = 1_769_046_526 * std.time.ns_per_s, + .max_retries = 3, + .retry_delay_seconds = 30, + .retry_backoff_multiplier = 2.0, + .load_level = .high, + }; + var aw: Io.Writer.Allocating = .init(arena.allocator()); + try writeManifestJson(&aw.writer, m); + try std.testing.expectEqualStrings( + \\{ + \\ "id" : "job-6d368040", + \\ "command" : [ "echo", "Hello World" ], + \\ "tag" : null, + \\ "createdAt" : "2026-01-22T01:48:46Z", + \\ "maxRetries" : 3, + \\ "retryDelaySeconds" : 30, + \\ "retryBackoffMultiplier" : 2.0, + \\ "loadLevel" : "HIGH" + \\} + , aw.written()); + const back = try parseManifestJson(arena.allocator(), aw.written()); + try std.testing.expectEqualStrings("job-6d368040", back.id); + try std.testing.expectEqual(m.created_at, back.created_at); + try std.testing.expectEqual(LoadLevel.high, back.load_level); + try std.testing.expectEqualStrings("Hello World", back.command[1]); +} + +test "manifest without loadLevel (older barn jobs) defaults to medium" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const m = try parseManifestJson(arena.allocator(), + \\{"id":"job-1","command":["ls"],"tag":"t","createdAt":"2026-01-22T01:48:46.749629Z", + \\ "maxRetries":0,"retryDelaySeconds":30,"retryBackoffMultiplier":2.0} + ); + try std.testing.expectEqual(LoadLevel.medium, m.load_level); + try std.testing.expectEqualStrings("t", m.tag.?); + try std.testing.expectError(error.InvalidManifest, parseManifestJson(arena.allocator(), "{}")); + try std.testing.expectError(error.InvalidManifest, parseManifestJson(arena.allocator(), + \\{"id":"j","command":[],"createdAt":"2026-01-22T01:48:46Z"} + )); +} + +test "create then find" { + const env = try TestEnv.init(); + defer env.deinit(); + const a = env.arena.allocator(); + + const created = try env.repo().create(a, &.{ "echo", "hi" }, .{ .tag = "downloading", .load_level = .low }); + try std.testing.expect(jobid.isValid(created.id)); + try std.testing.expectEqual(State.queued, created.state); + + const found = (try env.repo().findById(a, created.id)).?; + try std.testing.expectEqualStrings("downloading", found.tag.?); + try std.testing.expectEqual(LoadLevel.low, found.load_level); + try std.testing.expectEqual(@as(u32, 0), found.retry_count); + try std.testing.expectEqual(created.created_at, found.created_at); + try std.testing.expectEqualStrings("hi", found.command[1]); + try std.testing.expect((try env.repo().findById(a, "job-deadbeef")) == null); +} + +test "lifecycle: queued -> running -> succeeded" { + const env = try TestEnv.init(); + defer env.deinit(); + const a = env.arena.allocator(); + const r = env.repo(); + + const j = try r.create(a, &.{"true"}, .{}); + try r.markStarted(j.id, 4242); + var cur = (try r.findById(a, j.id)).?; + try std.testing.expectEqual(State.running, cur.state); + try std.testing.expectEqual(@as(i64, 4242), cur.pid.?); + try std.testing.expect(cur.started_at != null and cur.heartbeat != null); + + try r.markCompleted(j.id, 0, null); + cur = (try r.findById(a, j.id)).?; + try std.testing.expectEqual(State.succeeded, cur.state); + try std.testing.expectEqual(@as(i32, 0), cur.exit_code.?.code); + try std.testing.expect(cur.finished_at != null); +} + +test "invalid transitions are rejected and leave state untouched" { + const env = try TestEnv.init(); + defer env.deinit(); + const a = env.arena.allocator(); + const r = env.repo(); + + const j = try r.create(a, &.{"true"}, .{}); + try std.testing.expectError(error.InvalidTransition, r.markCompleted(j.id, 0, null)); + try r.markCanceled(j.id); + try std.testing.expectError(error.InvalidTransition, r.markStarted(j.id, 1)); + const cur = (try r.findById(a, j.id)).?; + try std.testing.expectEqual(State.canceled, cur.state); + try std.testing.expectEqualStrings("Job was canceled", cur.err.?); + try std.testing.expectError(error.JobNotFound, r.markCanceled("job-deadbeef")); +} + +test "failure with symbolic exit code" { + const env = try TestEnv.init(); + defer env.deinit(); + const a = env.arena.allocator(); + const r = env.repo(); + const j = try r.create(a, &.{"nope"}, .{}); + try r.markStarted(j.id, 1); + try r.markFailed(j.id, "start_failed", "Failed to start process"); + const cur = (try r.findById(a, j.id)).?; + try std.testing.expectEqual(State.failed, cur.state); + try std.testing.expectEqualStrings("start_failed", cur.exit_code.?.symbol); + try std.testing.expectEqualStrings("Failed to start process", cur.err.?); +} + +test "scheduleRetry requeues, counts and clears runtime state" { + const env = try TestEnv.init(); + defer env.deinit(); + const a = env.arena.allocator(); + const r = env.repo(); + + const j = try r.create(a, &.{"flaky"}, .{}); + try r.markStarted(j.id, 99); + try r.markCompleted(j.id, 3, "Process exited with code 3"); + const retry_at = timestamp.now(std.testing.io) + 30 * std.time.ns_per_s; + try r.scheduleRetry(std.testing.allocator, j.id, retry_at, 3, "Process exited\nwith | pipe"); + + const cur = (try r.findById(a, j.id)).?; + try std.testing.expectEqual(State.queued, cur.state); + try std.testing.expectEqual(@as(u32, 1), cur.retry_count); + try std.testing.expectEqual(retry_at, cur.retry_at.?); + try std.testing.expect(cur.started_at == null and cur.heartbeat == null and cur.finished_at == null); + + var job_dir = try env.dirs.openJob(std.testing.io, j.id); + defer job_dir.close(std.testing.io); + const hist = (try StateFiles.init(std.testing.io, job_dir).readRetryHistory(a)).?; + try std.testing.expect(std.mem.indexOf(u8, hist, "|attempt=1|exit_code=3|error=Process exited with ; pipe") != null); +} + +test "findAll, findByState and delete" { + const env = try TestEnv.init(); + defer env.deinit(); + const a = env.arena.allocator(); + const r = env.repo(); + + try std.testing.expectEqual(@as(usize, 0), (try r.findAll(a)).len); + const j1 = try r.create(a, &.{"a"}, .{}); + const j2 = try r.create(a, &.{"b"}, .{}); + try r.markStarted(j2.id, 5); + + try std.testing.expectEqual(@as(usize, 2), (try r.findAll(a)).len); + const running = try r.findByState(a, .running); + try std.testing.expectEqual(@as(usize, 1), running.len); + try std.testing.expectEqualStrings(j2.id, running[0].id); + + try r.delete(j1.id); + try std.testing.expectEqual(@as(usize, 1), (try r.findAll(a)).len); + try std.testing.expect((try r.findById(a, j1.id)) == null); +} diff --git a/src/root.zig b/src/root.zig index ac87f3d..15c11e3 100644 --- a/src/root.zig +++ b/src/root.zig @@ -6,6 +6,11 @@ pub const jobid = @import("jobid.zig"); pub const fsutil = @import("fsutil.zig"); pub const jsonpretty = @import("jsonpretty.zig"); pub const toml = @import("toml.zig"); +pub const loadlevel = @import("loadlevel.zig"); +pub const job = @import("job.zig"); +pub const dirs = @import("dirs.zig"); +pub const statefiles = @import("statefiles.zig"); +pub const repository = @import("repository.zig"); test { @import("std").testing.refAllDecls(@This()); diff --git a/src/statefiles.zig b/src/statefiles.zig new file mode 100644 index 0000000..dac42d6 --- /dev/null +++ b/src/statefiles.zig @@ -0,0 +1,258 @@ +//! One-value-per-file job state (`state`, `pid`, `heartbeat`, ...), always written atomically. +//! Absent files mean "unset"; writing null to a timestamp deletes its file. +const std = @import("std"); +const Io = std.Io; +const Dir = Io.Dir; +const Allocator = std.mem.Allocator; +const fsutil = @import("fsutil.zig"); +const timestamp = @import("timestamp.zig"); +const State = @import("state.zig").State; +const job = @import("job.zig"); + +pub const Instant = job.Instant; +pub const ExitCode = job.ExitCode; + +pub const names = struct { + pub const state = "state"; + pub const tag = "tag"; + pub const created_at = "created_at"; + pub const started_at = "started_at"; + pub const finished_at = "finished_at"; + pub const exit_code = "exit_code"; + pub const err = "error"; + pub const pid = "pid"; + pub const heartbeat = "heartbeat"; + pub const retry_count = "retry_count"; + pub const retry_at = "retry_at"; + pub const retry_history = "retry_history"; + pub const stage = "stage"; +}; + +pub const StateFiles = struct { + /// The job directory (`jobs/`). + dir: Dir, + io: Io, + + pub fn init(io: Io, dir: Dir) StateFiles { + return .{ .dir = dir, .io = io }; + } + + // -- generic helpers -- + + pub fn writeText(self: StateFiles, name: []const u8, text: []const u8) !void { + try fsutil.writeAtomic(self.io, self.dir, name, text); + } + + /// Returns the trimmed file content (allocated from `gpa`) or null if unset. + pub fn readText(self: StateFiles, gpa: Allocator, name: []const u8) !?[]u8 { + return fsutil.readTrimmed(self.io, gpa, self.dir, name); + } + + pub fn clear(self: StateFiles, name: []const u8) !void { + try fsutil.deleteIfExists(self.io, self.dir, name); + } + + fn writeInt(self: StateFiles, name: []const u8, n: anytype) !void { + var buf: [32]u8 = undefined; + try self.writeText(name, try std.fmt.bufPrint(&buf, "{d}", .{n})); + } + + fn readInt(self: StateFiles, comptime T: type, name: []const u8) !?T { + var buf: [64]u8 = undefined; + const text = (try self.readTextBuf(name, &buf)) orelse return null; + return std.fmt.parseInt(T, text, 10) catch null; + } + + fn readTextBuf(self: StateFiles, name: []const u8, buf: []u8) !?[]const u8 { + return fsutil.readTrimmedBuf(self.io, self.dir, name, buf); + } + + fn writeTime(self: StateFiles, name: []const u8, t: ?Instant) !void { + const v = t orelse return self.clear(name); + var buf: [timestamp.max_len]u8 = undefined; + try self.writeText(name, timestamp.format(&buf, v)); + } + + fn readTime(self: StateFiles, name: []const u8) !?Instant { + var buf: [64]u8 = undefined; + const text = (try self.readTextBuf(name, &buf)) orelse return null; + return timestamp.parse(text) catch null; + } + + // -- state -- + + pub fn writeState(self: StateFiles, s: State) !void { + try self.writeText(names.state, s.lower()); + } + + pub fn readState(self: StateFiles) !?State { + var buf: [32]u8 = undefined; + const text = (try self.readTextBuf(names.state, &buf)) orelse return null; + return State.parse(text); + } + + // -- text fields -- + + pub fn writeTag(self: StateFiles, tag: []const u8) !void { + try self.writeText(names.tag, tag); + } + + pub fn readTag(self: StateFiles, gpa: Allocator) !?[]u8 { + return self.readText(gpa, names.tag); + } + + pub fn writeError(self: StateFiles, msg: []const u8) !void { + try self.writeText(names.err, msg); + } + + pub fn readError(self: StateFiles, gpa: Allocator) !?[]u8 { + return self.readText(gpa, names.err); + } + + // -- timestamps (null clears) -- + + pub fn writeCreatedAt(self: StateFiles, t: ?Instant) !void { + try self.writeTime(names.created_at, t); + } + pub fn readCreatedAt(self: StateFiles) !?Instant { + return self.readTime(names.created_at); + } + pub fn writeStartedAt(self: StateFiles, t: ?Instant) !void { + try self.writeTime(names.started_at, t); + } + pub fn readStartedAt(self: StateFiles) !?Instant { + return self.readTime(names.started_at); + } + pub fn writeFinishedAt(self: StateFiles, t: ?Instant) !void { + try self.writeTime(names.finished_at, t); + } + pub fn readFinishedAt(self: StateFiles) !?Instant { + return self.readTime(names.finished_at); + } + pub fn writeHeartbeat(self: StateFiles, t: ?Instant) !void { + try self.writeTime(names.heartbeat, t); + } + pub fn readHeartbeat(self: StateFiles) !?Instant { + return self.readTime(names.heartbeat); + } + pub fn writeRetryAt(self: StateFiles, t: ?Instant) !void { + try self.writeTime(names.retry_at, t); + } + pub fn readRetryAt(self: StateFiles) !?Instant { + return self.readTime(names.retry_at); + } + + // -- numbers -- + + pub fn writeExitCode(self: StateFiles, code: ExitCode) !void { + switch (code) { + .code => |n| try self.writeInt(names.exit_code, n), + .symbol => |s| try self.writeText(names.exit_code, s), + } + } + + /// Numeric or symbolic exit code; the symbol slice is allocated from `gpa`. + pub fn readExitCode(self: StateFiles, gpa: Allocator) !?ExitCode { + const text = (try self.readText(gpa, names.exit_code)) orelse return null; + const parsed = ExitCode.parse(text); + if (parsed == .code) gpa.free(text); + return parsed; + } + + pub fn writePid(self: StateFiles, pid: i64) !void { + try self.writeInt(names.pid, pid); + } + pub fn readPid(self: StateFiles) !?i64 { + return self.readInt(i64, names.pid); + } + pub fn writeRetryCount(self: StateFiles, n: u32) !void { + try self.writeInt(names.retry_count, n); + } + pub fn readRetryCount(self: StateFiles) !?u32 { + return self.readInt(u32, names.retry_count); + } + + // -- retry history -- + + pub fn appendRetryHistory(self: StateFiles, gpa: Allocator, entry: []const u8) !void { + const existing = try self.readText(gpa, names.retry_history); + defer if (existing) |e| gpa.free(e); + if (existing) |e| if (e.len > 0) { + const joined = try std.fmt.allocPrint(gpa, "{s}\n{s}", .{ e, entry }); + defer gpa.free(joined); + return self.writeText(names.retry_history, joined); + }; + try self.writeText(names.retry_history, entry); + } + + pub fn readRetryHistory(self: StateFiles, gpa: Allocator) !?[]u8 { + return self.readText(gpa, names.retry_history); + } +}; + +fn expectEqOpt(comptime T: type, expected: ?T, actual: ?T) !void { + try std.testing.expectEqual(expected, actual); +} + +test "state round-trips through the lowercase file" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sf = StateFiles.init(io, tmp.dir); + try std.testing.expect((try sf.readState()) == null); + try sf.writeState(.running); + try expectEqOpt(State, .running, try sf.readState()); + const raw = (try sf.readText(std.testing.allocator, "state")).?; + defer std.testing.allocator.free(raw); + try std.testing.expectEqualStrings("running", raw); +} + +test "timestamps round-trip and null clears" { + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sf = StateFiles.init(io, tmp.dir); + const t: Instant = 1_769_046_526 * std.time.ns_per_s + 749_629_000; + try sf.writeStartedAt(t); + try expectEqOpt(Instant, t, try sf.readStartedAt()); + try sf.writeStartedAt(null); + try expectEqOpt(Instant, null, try sf.readStartedAt()); + // Unparseable content reads as unset, like barn. + try sf.writeText("heartbeat", "garbage"); + try expectEqOpt(Instant, null, try sf.readHeartbeat()); +} + +test "numbers, pid and exit codes" { + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sf = StateFiles.init(io, tmp.dir); + + try sf.writePid(17486); + try expectEqOpt(i64, 17486, try sf.readPid()); + try sf.writeRetryCount(3); + try expectEqOpt(u32, 3, try sf.readRetryCount()); + try std.testing.expect((try sf.readExitCode(gpa)) == null); + + try sf.writeExitCode(.{ .code = 2 }); + try std.testing.expectEqual(@as(i32, 2), (try sf.readExitCode(gpa)).?.code); + + try sf.writeExitCode(.{ .symbol = "start_failed" }); + const sym = (try sf.readExitCode(gpa)).?; + defer gpa.free(sym.symbol); + try std.testing.expectEqualStrings("start_failed", sym.symbol); +} + +test "retry history appends lines" { + const io = std.testing.io; + const gpa = std.testing.allocator; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sf = StateFiles.init(io, tmp.dir); + try sf.appendRetryHistory(gpa, "a"); + try sf.appendRetryHistory(gpa, "b"); + const h = (try sf.readRetryHistory(gpa)).?; + defer gpa.free(h); + try std.testing.expectEqualStrings("a\nb", h); +} diff --git a/src/timestamp.zig b/src/timestamp.zig index 85c1e3c..adec358 100644 --- a/src/timestamp.zig +++ b/src/timestamp.zig @@ -118,3 +118,8 @@ test "parse rejects garbage" { try std.testing.expectError(error.InvalidTimestamp, parse(bad)); } } + +/// Current wall-clock time as nanoseconds since the Unix epoch. +pub fn now(io: std.Io) i128 { + return std.Io.Timestamp.now(io, .real).nanoseconds; +}