diff --git a/AGENTS.md b/AGENTS.md index 80db413..e71944d 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -45,3 +45,4 @@ Guidance for AI coding agents working in `zag`, the Zig port of the | `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 | +| `src/service.zig` | Daemon core: recovery, scheduler, IPC handlers, cleanup timer, reload | diff --git a/src/loadclass.zig b/src/loadclass.zig index d038e31..87534c5 100644 --- a/src/loadclass.zig +++ b/src/loadclass.zig @@ -89,6 +89,23 @@ pub const Classifier = struct { }; } + /// True when at least one of the three `.load` files exists in `config_dir`. + pub fn anyFileExists(io: Io, config_dir: []const u8) bool { + var buf: [512]u8 = undefined; + for ([_][]const u8{ "high.load", "medium.load", "low.load" }) |name| { + const path = std.fmt.bufPrint(&buf, "{s}/{s}", .{ config_dir, name }) catch continue; + if (Io.Dir.cwd().statFile(io, path, .{})) |_| return true else |_| {} + } + return false; + } + + /// Loads from `config_dir` when it holds any `.load` file, else uses the embedded defaults + /// (so `ffmpeg` is HIGH and `curl` is LOW even before `zag config install`). + pub fn loadOrDefaults(arena: Allocator, io: Io, config_dir: []const u8) Allocator.Error!Classifier { + if (anyFileExists(io, config_dir)) return load(arena, io, config_dir); + return fromDefaults(arena); + } + /// Classifier built from the embedded default files. pub fn fromDefaults(arena: Allocator) Allocator.Error!Classifier { const defaults = @import("defaults.zig"); @@ -187,3 +204,20 @@ test "load reads files from a directory and tolerates missing ones" { try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"mytool"}))); try std.testing.expectEqual(@as(usize, 0), c.low.len); } + +test "loadOrDefaults falls back to the embedded lists when no file exists" { + const io = std.testing.io; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + + const defaults = try Classifier.loadOrDefaults(a, io, dir); + try std.testing.expectEqual(LoadLevel.high, defaults.classify(cmd(&.{"ffmpeg"}))); + + try tmp.dir.writeFile(io, .{ .sub_path = "low.load", .data = "ffmpeg\n" }); + const custom = try Classifier.loadOrDefaults(a, io, dir); + try std.testing.expectEqual(LoadLevel.low, custom.classify(cmd(&.{"ffmpeg"}))); +} diff --git a/src/proc.zig b/src/proc.zig index dd5ed86..0630e8f 100644 --- a/src/proc.zig +++ b/src/proc.zig @@ -56,6 +56,14 @@ pub fn appendLog(io: Io, job_dir: Dir, sub_path: []const u8, line: []const u8) ! try f.writeStreamingAll(io, "\n"); } +pub fn currentPid() i64 { + return switch (builtin.os.tag) { + .linux => std.os.linux.getpid(), + .windows, .wasi => 0, + else => std.c.getpid(), + }; +} + pub const Signal = enum { term, kill }; /// Signals the process group led by `pid`, falling back to the single process. diff --git a/src/root.zig b/src/root.zig index 5a52595..83308ad 100644 --- a/src/root.zig +++ b/src/root.zig @@ -23,6 +23,7 @@ pub const usage = @import("usage.zig"); pub const cleanup = @import("cleanup.zig"); pub const jobjson = @import("jobjson.zig"); pub const ipc = @import("ipc.zig"); +pub const service = @import("service.zig"); test { @import("std").testing.refAllDecls(@This()); diff --git a/src/scheduler.zig b/src/scheduler.zig index 8839f22..7b396b4 100644 --- a/src/scheduler.zig +++ b/src/scheduler.zig @@ -107,6 +107,26 @@ pub const Scheduler = struct { return self.counts[@intFromEnum(level)]; } + /// Applies new concurrency limits; running jobs are unaffected. + pub fn setLimits(self: *Scheduler, limits: LoadLevels) void { + self.mutex.lockUncancelable(self.io); + defer self.mutex.unlock(self.io); + self.opts.limits = limits; + } + + /// Applies new runner settings (heartbeat, timeout, retry codes) to jobs started from now on. + pub fn setRunnerOptions(self: *Scheduler, ro: runner.Options) void { + self.mutex.lockUncancelable(self.io); + defer self.mutex.unlock(self.io); + self.opts.runner = ro; + } + + fn runnerOptions(self: *Scheduler) runner.Options { + self.mutex.lockUncancelable(self.io); + defer self.mutex.unlock(self.io); + return self.opts.runner; + } + pub fn limitFor(self: *const Scheduler, level: LoadLevel) u32 { return switch (level) { .high => self.opts.limits.max_high_jobs, @@ -176,7 +196,7 @@ pub const Scheduler = struct { } fn runJob(self: *Scheduler, entry: *Active) void { - _ = runner.run(self.gpa, self.io, self.repo, entry.id, &entry.ctl, self.opts.runner); + _ = runner.run(self.gpa, self.io, self.repo, entry.id, &entry.ctl, self.runnerOptions()); self.release(entry); } @@ -379,3 +399,22 @@ test "only one scheduler per base dir" { try s2.start(); // lock released by stop _ = s2.stop(1000); } + +test "limits can be changed while running" { + const env = try Env.init(); + defer env.deinit(); + const a = env.arena.allocator(); + var opts = test_opts; + opts.limits = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 }; + var s = Scheduler.init(std.testing.allocator, std.testing.io, env.repo(), opts); + defer s.deinit(); + try s.start(); + const j1 = try env.repo().create(a, &.{ "sleep", "0.8" }, .{}); + const j2 = try env.repo().create(a, &.{ "sleep", "0.8" }, .{}); + try env.waitFor(j1.id, .running, 3000); + try std.testing.io.sleep(.fromMilliseconds(150), .real); + try std.testing.expectEqual(State.queued, try env.state(j2.id)); // capped at 1 + s.setLimits(.{ .max_high_jobs = 1, .max_medium_jobs = 2, .max_low_jobs = 1 }); + try env.waitFor(j2.id, .running, 3000); // now allowed alongside j1 + _ = s.stop(5000); +} diff --git a/src/service.zig b/src/service.zig new file mode 100644 index 0000000..c2522cd --- /dev/null +++ b/src/service.zig @@ -0,0 +1,620 @@ +//! The zag daemon core: wires the repository, scheduler, crash recovery, cleanup timer and the +//! IPC server together. Port of barn's `BarnService`. +//! +//! Start order: directories, crash recovery, scheduler (takes the scheduler lock), IPC server, +//! cleanup timer. Stop order is the reverse. Configuration can be reloaded at runtime: limits, +//! retry/timeout defaults, heartbeat and cleanup settings apply immediately; paths need a restart. +const std = @import("std"); +const Io = std.Io; +const Allocator = std.mem.Allocator; +const config = @import("config.zig"); +const Dirs = @import("dirs.zig").Dirs; +const Repository = @import("repository.zig").Repository; +const scheduler_mod = @import("scheduler.zig"); +const Scheduler = scheduler_mod.Scheduler; +const runner = @import("runner.zig"); +const recovery = @import("recovery.zig"); +const cleanup = @import("cleanup.zig"); +const ipc = @import("ipc.zig"); +const jobjson = @import("jobjson.zig"); +const jsonpretty = @import("jsonpretty.zig"); +const duration = @import("duration.zig"); +const timestamp = @import("timestamp.zig"); +const proc = @import("proc.zig"); +const state_mod = @import("state.zig"); +const LoadLevel = @import("loadlevel.zig").LoadLevel; +const Classifier = @import("loadclass.zig").Classifier; +const Job = @import("job.zig").Job; +const Instant = @import("job.zig").Instant; + +pub const ReloadFn = *const fn (ctx: ?*anyopaque, arena: Allocator) anyerror!config.Config; + +pub const Options = struct { + config: config.Config = .{}, + classifier: Classifier = .{}, + reload_fn: ?ReloadFn = null, + reload_ctx: ?*anyopaque = null, + scheduler_tick_ms: u64 = 1_000, + runner_tick_ms: u64 = 100, + kill_grace_ms: u64 = 5_000, + /// Overrides `cleanup.cleanup_interval_minutes` (tests). + cleanup_interval_ms: ?u64 = null, + /// How long `stop` waits for running jobs. + stop_wait_ms: u64 = 5 * 60 * 1000, +}; + +pub const Service = struct { + gpa: Allocator, + io: Io, + dirs: *Dirs, + repo: Repository, + opts: Options, + scheduler: Scheduler, + ipc_server: ipc.Server, + random_source: std.Random.IoSource, + + cfg_mutex: Io.Mutex = .init, + cfg: config.Config, + /// Arenas holding reloaded config strings; kept until deinit because running jobs may + /// still reference them. + cfg_arenas: std.ArrayList(*std.heap.ArenaAllocator) = .empty, + + started_at: Instant = 0, + running: std.atomic.Value(bool) = .init(false), + shutdown_requested: std.atomic.Value(bool) = .init(false), + cleanup_thread: ?std.Thread = null, + cleanup_stop: std.atomic.Value(bool) = .init(false), + + pub fn init(gpa: Allocator, io: Io, dirs: *Dirs, opts: Options) Service { + const repo = Repository.init(io, dirs); + return .{ + .gpa = gpa, + .io = io, + .dirs = dirs, + .repo = repo, + .opts = opts, + .cfg = opts.config, + .scheduler = undefined, + .ipc_server = undefined, + .random_source = .{ .io = io }, + }; + } + + /// Finishes construction once the Service has its final address (the IPC handler and the + /// scheduler keep pointers into it). Call before `start`. + pub fn bind(self: *Service, socket_path: []const u8) void { + self.scheduler = Scheduler.init(self.gpa, self.io, self.repo, self.schedulerOptions(self.cfg)); + self.ipc_server = ipc.Server.init(self.gpa, self.io, socket_path, self, handleIpc); + } + + fn runnerOptions(self: *Service, cfg: config.Config) runner.Options { + return .{ + .heartbeat_interval_ms = @as(u64, cfg.service.heartbeat_interval_seconds) * 1000, + .timeout_seconds = cfg.jobs.default_timeout_seconds, + .retry_codes = cfg.jobs.retry_on_exit_codes, + .tick_ms = self.opts.runner_tick_ms, + .kill_grace_ms = self.opts.kill_grace_ms, + .random = self.random_source.interface(), + }; + } + + fn schedulerOptions(self: *Service, cfg: config.Config) scheduler_mod.Options { + return .{ + .limits = cfg.load_levels, + .tick_ms = self.opts.scheduler_tick_ms, + .runner = self.runnerOptions(cfg), + }; + } + + pub fn deinit(self: *Service) void { + self.scheduler.deinit(); + for (self.cfg_arenas.items) |a| { + a.deinit(); + self.gpa.destroy(a); + } + self.cfg_arenas.deinit(self.gpa); + } + + pub const StartError = Scheduler.StartError || ipc.Server.StartError || std.Thread.SpawnError || anyerror; + + pub fn start(self: *Service) StartError!void { + std.debug.assert(!self.running.load(.acquire)); + try self.dirs.initialize(self.io); + + const stale = self.currentConfig().service.stale_heartbeat_threshold_seconds; + const recovered = try recovery.recoverOrphanedJobs(self.gpa, self.io, self.repo, .{ + .stale_threshold_seconds = stale, + .random = self.random_source.interface(), + }); + if (recovered > 0) std.log.info("recovered {d} orphaned job(s)", .{recovered}); + + try self.scheduler.start(); + errdefer _ = self.scheduler.stop(0); + try self.ipc_server.start(); + errdefer self.ipc_server.stop(); + + self.cleanup_stop.store(false, .release); + if (self.currentConfig().cleanup.enabled) { + self.cleanup_thread = try std.Thread.spawn(.{}, cleanupLoop, .{self}); + } + self.started_at = timestamp.now(self.io); + self.shutdown_requested.store(false, .release); + self.running.store(true, .release); + } + + /// Blocks until `requestShutdown` is called. + pub fn awaitShutdown(self: *Service) void { + while (!self.shutdown_requested.load(.acquire)) { + self.io.sleep(.fromMilliseconds(50), .real) catch return; + } + } + + /// Async-signal-safe: only flips an atomic. + pub fn requestShutdown(self: *Service) void { + self.shutdown_requested.store(true, .release); + } + + /// Stops accepting requests, then waits for running jobs. Returns jobs still running. + pub fn stop(self: *Service) usize { + if (!self.running.swap(false, .acq_rel)) return 0; + self.ipc_server.stop(); + self.cleanup_stop.store(true, .release); + if (self.cleanup_thread) |t| t.join(); + self.cleanup_thread = null; + return self.scheduler.stop(self.opts.stop_wait_ms); + } + + pub fn currentConfig(self: *Service) config.Config { + self.cfg_mutex.lockUncancelable(self.io); + defer self.cfg_mutex.unlock(self.io); + return self.cfg; + } + + /// Re-reads configuration through `reload_fn` and applies the runtime-adjustable parts. + pub fn reload(self: *Service) !void { + const f = self.opts.reload_fn orelse return error.ReloadUnsupported; + const arena = try self.gpa.create(std.heap.ArenaAllocator); + arena.* = std.heap.ArenaAllocator.init(self.gpa); + errdefer { + arena.deinit(); + self.gpa.destroy(arena); + } + const new_cfg = try f(self.opts.reload_ctx, arena.allocator()); + try self.cfg_arenas.append(self.gpa, arena); + + self.cfg_mutex.lockUncancelable(self.io); + self.cfg = new_cfg; + self.cfg_mutex.unlock(self.io); + + self.scheduler.setLimits(new_cfg.load_levels); + self.scheduler.setRunnerOptions(self.runnerOptions(new_cfg)); + } + + // -- cleanup timer --------------------------------------------------------------- + + fn cleanupLoop(self: *Service) void { + while (!self.cleanup_stop.load(.acquire)) { + const cfg = self.currentConfig(); + const interval_ms: u64 = self.opts.cleanup_interval_ms orelse @as(u64, cfg.cleanup.cleanup_interval_minutes) * 60_000; + var slept: u64 = 0; + while (slept < interval_ms and !self.cleanup_stop.load(.acquire)) : (slept += 20) { + self.io.sleep(.fromMilliseconds(20), .real) catch return; + } + if (self.cleanup_stop.load(.acquire)) return; + const current = self.currentConfig(); + if (!current.cleanup.enabled) continue; + const n = cleanup.runAutomatic(self.gpa, self.io, self.repo, current.cleanup, timestamp.now(self.io)) catch |err| { + std.log.err("cleanup failed: {s}", .{@errorName(err)}); + continue; + }; + if (n > 0) std.log.info("cleaned {d} job(s)", .{n}); + } + } + + // -- IPC ------------------------------------------------------------------------- + + fn handleIpc(ctx: *anyopaque, req: ipc.Request, res: *ipc.Response) ipc.HandlerError!void { + const self: *Service = @ptrCast(@alignCast(ctx)); + const t = req.type; + if (std.mem.eql(u8, t, "get_service_status")) return self.hServiceStatus(res); + if (std.mem.eql(u8, t, "shutdown")) { + self.requestShutdown(); + return res.json.string("Shutdown initiated"); + } + if (std.mem.eql(u8, t, "reload")) { + self.reload() catch |err| return res.failFmt(.INTERNAL_ERROR, "Reload failed: {s}", .{@errorName(err)}); + return res.json.string("Configuration reloaded"); + } + if (std.mem.eql(u8, t, "get_status")) return self.hGetStatus(req, res); + if (std.mem.eql(u8, t, "get_job")) return self.hGetJob(req, res); + if (std.mem.eql(u8, t, "run_job")) return self.hRunJob(req, res); + if (std.mem.eql(u8, t, "kill_job")) return self.hKillJob(req, res); + if (std.mem.eql(u8, t, "clean_jobs")) return self.hCleanJobs(req, res); + return res.failFmt(.INVALID_REQUEST, "Unknown request type: {s}", .{t}); + } + + fn hServiceStatus(self: *Service, res: *ipc.Response) !void { + var counts = [_]u32{0} ** 6; + const jobs = try self.repo.findAll(res.arena); + for (jobs) |j| counts[@intFromEnum(j.state)] += 1; + const now = timestamp.now(self.io); + var w = &res.json; + try w.beginObject(); + try w.field("running", .boolean, self.running.load(.acquire)); + try w.field("pid", .int, proc.currentPid()); + try w.key("startedAt"); + try jobjson.writeInstant(w, self.started_at); + try w.field("uptimeSeconds", .int, @divFloor(now - self.started_at, std.time.ns_per_s)); + try w.field("dataDir", .string, self.dirs.base_path); + try w.field("activeJobs", .int, counts[@intFromEnum(state_mod.State.running)]); + try w.field("queuedJobs", .int, counts[@intFromEnum(state_mod.State.queued)]); + try w.key("jobs"); + try w.beginObject(); + inline for (@typeInfo(state_mod.State).@"enum".fields) |f| try w.field(f.name, .int, counts[f.value]); + try w.field("total", .int, jobs.len); + try w.endObject(); + try w.endObject(); + } + + fn newerFirst(_: void, a: Job, b: Job) bool { + return a.created_at > b.created_at; + } + + fn hGetStatus(self: *Service, req: ipc.Request, res: *ipc.Response) !void { + const tag = req.payloadString("tag"); + var want: ?state_mod.State = null; + if (req.payloadString("state")) |s| want = state_mod.State.parse(s) orelse + return res.failFmt(.INVALID_REQUEST, "Unknown state: {s}", .{s}); + + var list: std.ArrayList(Job) = .empty; + for (try self.repo.findAll(res.arena)) |j| { + if (tag) |t| if (j.tag == null or !std.mem.eql(u8, t, j.tag.?)) continue; + if (want) |s| if (j.state != s) continue; + try list.append(res.arena, j); + } + std.mem.sort(Job, list.items, {}, newerFirst); + var out: []const Job = list.items; + if (req.payloadInt("limit")) |n| if (n > 0 and out.len > n) { + out = out[0..@intCast(n)]; + }; + try jobjson.writeJobs(&res.json, out); + } + + fn hGetJob(self: *Service, req: ipc.Request, res: *ipc.Response) !void { + const id = req.payloadString("jobId") orelse switch (req.payload) { + .string => |s| s, + else => return res.fail(.INVALID_REQUEST, "Job ID is required"), + }; + const job = (try self.repo.findById(res.arena, id)) orelse + return res.failFmt(.NOT_FOUND, "Job not found: {s}", .{id}); + try jobjson.writeJob(&res.json, job); + } + + fn hRunJob(self: *Service, req: ipc.Request, res: *ipc.Response) !void { + const obj = switch (req.payload) { + .object => |o| o, + else => return res.fail(.INVALID_REQUEST, "Invalid payload"), + }; + const cmd_val = obj.get("command") orelse return res.fail(.INVALID_REQUEST, "Command is required"); + const items = switch (cmd_val) { + .array => |a| a.items, + else => return res.fail(.INVALID_REQUEST, "Command must be an array of strings"), + }; + if (items.len == 0) return res.fail(.INVALID_REQUEST, "Command is required"); + const command = try res.arena.alloc([]const u8, items.len); + for (items, command) |v, *slot| slot.* = switch (v) { + .string => |s| s, + else => return res.fail(.INVALID_REQUEST, "Command must be an array of strings"), + }; + + const cfg = self.currentConfig(); + var create_opts: @import("repository.zig").CreateOptions = .{ + .tag = req.payloadString("tag"), + .max_retries = cfg.jobs.max_retries, + .retry_delay_seconds = cfg.jobs.retry_delay_seconds, + .retry_backoff_multiplier = cfg.jobs.retry_backoff_multiplier, + }; + if (req.payloadInt("maxRetries")) |n| { + create_opts.max_retries = std.math.cast(u32, n) orelse return res.fail(.INVALID_REQUEST, "maxRetries must be non-negative"); + } + if (req.payloadInt("retryDelaySeconds")) |n| { + create_opts.retry_delay_seconds = std.math.cast(u32, n) orelse return res.fail(.INVALID_REQUEST, "retryDelaySeconds must be non-negative"); + } + create_opts.load_level = if (req.payloadString("loadLevel")) |l| + LoadLevel.parse(l) orelse return res.failFmt(.INVALID_REQUEST, "Invalid load level: '{s}'. Valid values are: high, medium, low", .{l}) + else + self.opts.classifier.classify(command); + + const job = try self.repo.create(res.arena, command, create_opts); + try jobjson.writeJob(&res.json, job); + } + + fn hKillJob(self: *Service, req: ipc.Request, res: *ipc.Response) !void { + const id = req.payloadString("jobId") orelse switch (req.payload) { + .string => |s| s, + else => return res.fail(.INVALID_REQUEST, "Job ID is required"), + }; + const result = try self.scheduler.killJob(id, req.payloadBool("force")); + switch (result) { + .not_found => return res.failFmt(.NOT_FOUND, "Job not found: {s}", .{id}), + .not_running => { + const job = (try self.repo.findById(res.arena, id)) orelse return res.failFmt(.NOT_FOUND, "Job not found: {s}", .{id}); + return res.failFmt(.INVALID_STATE, "Job is not running: {s}", .{job.state.lower()}); + }, + .signalled, .canceled => {}, + } + const job = (try self.repo.findById(res.arena, id)) orelse return res.failFmt(.NOT_FOUND, "Job not found: {s}", .{id}); + try jobjson.writeJob(&res.json, job); + } + + fn hCleanJobs(self: *Service, req: ipc.Request, res: *ipc.Response) !void { + var policy: cleanup.ManualPolicy = .{ + .all = req.payloadBool("all"), + .include_failed = req.payloadBool("includeFailed"), + .job_id = req.payloadString("jobId"), + }; + if (req.payloadString("olderThan")) |s| { + policy.older_than_seconds = duration.parseSeconds(s) catch + return res.failFmt(.INVALID_REQUEST, "Invalid duration: {s}", .{s}); + } + const dry_run = req.payloadBool("dryRun"); + + const plan = cleanup.planManual(res.arena, self.io, self.repo, policy, timestamp.now(self.io)) catch |err| switch (err) { + error.JobNotFound => return res.failFmt(.NOT_FOUND, "Job not found: {s}", .{policy.job_id.?}), + error.NotCleanable => return res.failFmt(.INVALID_STATE, "Cannot clean job {s}: it is running, queued, or failed (use includeFailed)", .{policy.job_id.?}), + else => |e| return e, + }; + var bytes: u64 = 0; + for (plan) |c| bytes += c.size_bytes; + if (!dry_run) _ = cleanup.execute(self.repo, plan); + + var w = &res.json; + try w.beginObject(); + try w.field("dryRun", .boolean, dry_run); + try w.field("count", .int, plan.len); + try w.field("bytesFreed", .int, bytes); + try w.key("cleaned"); + try w.beginArray(); + for (plan) |c| { + try w.beginObject(); + try w.key("job"); + try jobjson.writeJob(w, c.job); + try w.field("sizeBytes", .int, c.size_bytes); + try w.endObject(); + } + try w.endArray(); + try w.endObject(); + } +}; + +// -- tests ----------------------------------------------------------------------------- + +const Harness = struct { + tmp: std.testing.TmpDir, + arena: std.heap.ArenaAllocator, + dirs: Dirs, + svc: Service, + sock: []const u8, + + fn create(opts_in: Options) !*Harness { + const h = try std.testing.allocator.create(Harness); + h.tmp = std.testing.tmpDir(.{}); + h.arena = std.heap.ArenaAllocator.init(std.testing.allocator); + const a = h.arena.allocator(); + const base = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/zag", .{h.tmp.sub_path}); + h.dirs = try Dirs.open(std.testing.io, base); + h.sock = try std.fmt.allocPrint(a, "{s}/zag.sock", .{base}); + var opts = opts_in; + opts.scheduler_tick_ms = 20; + opts.runner_tick_ms = 10; + opts.kill_grace_ms = 300; + opts.stop_wait_ms = 5000; + h.svc = Service.init(std.testing.allocator, std.testing.io, &h.dirs, opts); + h.svc.bind(h.sock); + try h.svc.start(); + return h; + } + + fn destroy(self: *Harness) void { + _ = self.svc.stop(); + self.svc.deinit(); + self.dirs.close(std.testing.io); + self.arena.deinit(); + self.tmp.cleanup(); + std.testing.allocator.destroy(self); + } + + fn call(self: *Harness, t: []const u8, payload: ?[]const u8) !ipc.Reply { + return ipc.call(std.testing.io, self.arena.allocator(), self.sock, t, payload); + } + + fn okObj(self: *Harness, t: []const u8, payload: ?[]const u8) !std.json.ObjectMap { + return (try self.call(t, payload)).ok.object; + } + + fn waitState(self: *Harness, id: []const u8, want: []const u8) !void { + const payload = try std.fmt.allocPrint(self.arena.allocator(), "{{\"jobId\":\"{s}\"}}", .{id}); + var waited: u64 = 0; + while (waited < 8000) : (waited += 20) { + const r = try self.call("get_job", payload); + if (std.mem.eql(u8, r.ok.object.get("state").?.string, want)) return; + try std.testing.io.sleep(.fromMilliseconds(20), .real); + } + return error.Timeout; + } +}; + +test "run a job end to end over IPC" { + const h = try Harness.create(.{}); + defer h.destroy(); + + const queued = try h.okObj("run_job", "{\"command\":[\"sh\",\"-c\",\"echo hi\"],\"tag\":\"demo\"}"); + const id = queued.get("id").?.string; + try std.testing.expectEqualStrings("QUEUED", queued.get("state").?.string); + try std.testing.expectEqualStrings("demo", queued.get("tag").?.string); + + try h.waitState(id, "SUCCEEDED"); + const list = (try h.call("get_status", "{\"tag\":\"demo\"}")).ok.array.items; + try std.testing.expectEqual(@as(usize, 1), list.len); + try std.testing.expectEqual(@as(i64, 0), list[0].object.get("exitCode").?.integer); + + const status = try h.okObj("get_service_status", null); + try std.testing.expect(status.get("running").?.bool); + try std.testing.expectEqual(@as(i64, 1), status.get("jobs").?.object.get("total").?.integer); + try std.testing.expectEqual(@as(i64, 1), status.get("jobs").?.object.get("succeeded").?.integer); + try std.testing.expect(status.get("pid").?.integer > 0); +} + +test "load level is auto-classified or overridden" { + var classifier: Classifier = .{}; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + classifier = try Classifier.fromDefaults(arena.allocator()); + const h = try Harness.create(.{ .classifier = classifier, .config = .{ .load_levels = .{ .max_high_jobs = 1, .max_medium_jobs = 1, .max_low_jobs = 1 } } }); + defer h.destroy(); + + const auto = try h.okObj("run_job", "{\"command\":[\"curl\",\"--version\"]}"); + try std.testing.expectEqualStrings("LOW", auto.get("loadLevel").?.string); + const forced = try h.okObj("run_job", "{\"command\":[\"curl\",\"--version\"],\"loadLevel\":\"high\"}"); + try std.testing.expectEqualStrings("HIGH", forced.get("loadLevel").?.string); + const plain = try h.okObj("run_job", "{\"command\":[\"echo\",\"x\"]}"); + try std.testing.expectEqualStrings("MEDIUM", plain.get("loadLevel").?.string); + const bad = try h.call("run_job", "{\"command\":[\"echo\"],\"loadLevel\":\"extreme\"}"); + try std.testing.expectEqualStrings("INVALID_REQUEST", bad.err.code); +} + +test "request validation and not-found errors" { + const h = try Harness.create(.{}); + defer h.destroy(); + try std.testing.expectEqualStrings("INVALID_REQUEST", (try h.call("run_job", null)).err.code); + try std.testing.expectEqualStrings("INVALID_REQUEST", (try h.call("run_job", "{\"command\":[]}")).err.code); + try std.testing.expectEqualStrings("INVALID_REQUEST", (try h.call("run_job", "{\"command\":[1]}")).err.code); + try std.testing.expectEqualStrings("INVALID_REQUEST", (try h.call("get_job", null)).err.code); + try std.testing.expectEqualStrings("NOT_FOUND", (try h.call("get_job", "{\"jobId\":\"job-deadbeef\"}")).err.code); + try std.testing.expectEqualStrings("NOT_FOUND", (try h.call("kill_job", "{\"jobId\":\"job-deadbeef\"}")).err.code); + try std.testing.expectEqualStrings("INVALID_REQUEST", (try h.call("get_status", "{\"state\":\"bogus\"}")).err.code); + try std.testing.expectEqualStrings("INVALID_REQUEST", (try h.call("frobnicate", null)).err.code); +} + +test "kill a running job, and INVALID_STATE for a finished one" { + const h = try Harness.create(.{}); + defer h.destroy(); + const j = try h.okObj("run_job", "{\"command\":[\"sleep\",\"30\"]}"); + const id = j.get("id").?.string; + try h.waitState(id, "RUNNING"); + + const payload = try std.fmt.allocPrint(h.arena.allocator(), "{{\"jobId\":\"{s}\"}}", .{id}); + _ = try h.okObj("kill_job", payload); + try h.waitState(id, "CANCELED"); + const again = try h.call("kill_job", payload); + try std.testing.expectEqualStrings("INVALID_STATE", again.err.code); +} + +test "get_status filters, sorts newest first and limits" { + const h = try Harness.create(.{}); + defer h.destroy(); + var ids: [3][]const u8 = undefined; + for (&ids) |*id| { + id.* = (try h.okObj("run_job", "{\"command\":[\"true\"]}")).get("id").?.string; + try std.testing.io.sleep(.fromMilliseconds(5), .real); + } + for (ids) |id| try h.waitState(id, "SUCCEEDED"); + const all = (try h.call("get_status", null)).ok.array.items; + try std.testing.expectEqual(@as(usize, 3), all.len); + try std.testing.expectEqualStrings(ids[2], all[0].object.get("id").?.string); + const limited = (try h.call("get_status", "{\"limit\":2,\"state\":\"succeeded\"}")).ok.array.items; + try std.testing.expectEqual(@as(usize, 2), limited.len); + const none = (try h.call("get_status", "{\"state\":\"failed\"}")).ok.array.items; + try std.testing.expectEqual(@as(usize, 0), none.len); +} + +test "clean_jobs semantics: nothing by default, --all, dry run, job id" { + const h = try Harness.create(.{}); + defer h.destroy(); + const a = h.arena.allocator(); + const ok_id = (try h.okObj("run_job", "{\"command\":[\"true\"]}")).get("id").?.string; + const fail_id = (try h.okObj("run_job", "{\"command\":[\"sh\",\"-c\",\"exit 1\"],\"maxRetries\":0}")).get("id").?.string; + try h.waitState(ok_id, "SUCCEEDED"); + try h.waitState(fail_id, "FAILED"); + + var r = try h.okObj("clean_jobs", "{}"); + try std.testing.expectEqual(@as(i64, 0), r.get("count").?.integer); + + r = try h.okObj("clean_jobs", "{\"all\":true,\"dryRun\":true}"); + try std.testing.expectEqual(@as(i64, 1), r.get("count").?.integer); + try std.testing.expect(h.dirs.jobExists(std.testing.io, ok_id)); + + const failed_payload = try std.fmt.allocPrint(a, "{{\"jobId\":\"{s}\"}}", .{fail_id}); + try std.testing.expectEqualStrings("INVALID_STATE", (try h.call("clean_jobs", failed_payload)).err.code); + + r = try h.okObj("clean_jobs", "{\"all\":true}"); + try std.testing.expectEqual(@as(i64, 1), r.get("count").?.integer); + try std.testing.expect(!h.dirs.jobExists(std.testing.io, ok_id)); + try std.testing.expect(h.dirs.jobExists(std.testing.io, fail_id)); + try std.testing.expectEqualStrings("INVALID_REQUEST", (try h.call("clean_jobs", "{\"olderThan\":\"soon\"}")).err.code); +} + +test "shutdown request flips the flag" { + const h = try Harness.create(.{}); + defer h.destroy(); + try std.testing.expect(!h.svc.shutdown_requested.load(.acquire)); + const r = try h.call("shutdown", null); + try std.testing.expectEqualStrings("Shutdown initiated", r.ok.string); + h.svc.awaitShutdown(); + try std.testing.expect(h.svc.shutdown_requested.load(.acquire)); +} + +fn testReload(ctx: ?*anyopaque, arena: Allocator) anyerror!config.Config { + _ = ctx; + _ = arena; + return .{ .jobs = .{ .max_retries = 9, .retry_delay_seconds = 7 } }; +} + +test "reload applies new job defaults; unsupported without a loader" { + const h = try Harness.create(.{ .reload_fn = testReload }); + defer h.destroy(); + const before = try h.okObj("run_job", "{\"command\":[\"true\"]}"); + _ = before; + try std.testing.expectEqualStrings("Configuration reloaded", (try h.call("reload", null)).ok.string); + try std.testing.expectEqual(@as(u32, 9), h.svc.currentConfig().jobs.max_retries); + + const id = (try h.okObj("run_job", "{\"command\":[\"true\"]}")).get("id").?.string; + const m = try h.svc.repo.loadManifest(h.arena.allocator(), id); + try std.testing.expectEqual(@as(u32, 9), m.max_retries); + try std.testing.expectEqual(@as(u32, 7), m.retry_delay_seconds); + + const h2 = try Harness.create(.{}); + defer h2.destroy(); + try std.testing.expectEqualStrings("INTERNAL_ERROR", (try h2.call("reload", null)).err.code); +} + +test "periodic cleanup removes old finished jobs" { + const h = try Harness.create(.{ .cleanup_interval_ms = 100, .config = .{ .cleanup = .{ .max_age_hours = 1 } } }); + defer h.destroy(); + const id = (try h.okObj("run_job", "{\"command\":[\"true\"]}")).get("id").?.string; + try h.waitState(id, "SUCCEEDED"); + // Backdate the finish time past the retention window. + var jd = try h.dirs.openJob(std.testing.io, id); + const sf = @import("statefiles.zig").StateFiles.init(std.testing.io, jd); + try sf.writeFinishedAt(timestamp.now(std.testing.io) - 2 * 3600 * std.time.ns_per_s); + jd.close(std.testing.io); + + var waited: u64 = 0; + while (h.dirs.jobExists(std.testing.io, id) and waited < 5000) : (waited += 20) { + try std.testing.io.sleep(.fromMilliseconds(20), .real); + } + try std.testing.expect(!h.dirs.jobExists(std.testing.io, id)); +} + +test "startup recovers orphaned jobs" { + const h = try Harness.create(.{}); + const a = h.arena.allocator(); + const j = try h.svc.repo.create(a, &.{"x"}, .{ .max_retries = 0 }); + try h.svc.repo.markStarted(j.id, 999_999_999); + try h.svc.repo.updateHeartbeat(j.id, timestamp.now(std.testing.io) - 600 * std.time.ns_per_s); + _ = h.svc.stop(); + try h.svc.start(); // simulated daemon restart + defer h.destroy(); + const now = (try h.svc.repo.findById(a, j.id)).?; + try std.testing.expectEqual(state_mod.State.killed, now.state); +}