//! 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 query = @import("query.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 hGetStatus(self: *Service, req: ipc.Request, res: *ipc.Response) !void { var filter: query.Filter = .{ .tag = req.payloadString("tag") }; if (req.payloadString("state")) |s| filter.state = state_mod.State.parse(s) orelse return res.failFmt(.INVALID_REQUEST, "Unknown state: {s}", .{s}); if (req.payloadInt("limit")) |n| if (n > 0) { filter.limit = @intCast(n); }; try jobjson.writeJobs(&res.json, try query.selectJobs(res.arena, self.repo, filter)); } 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"); } if (req.payloadInt("timeoutSeconds")) |n| { create_opts.timeout_seconds = std.math.cast(u32, n) orelse return res.fail(.INVALID_REQUEST, "timeoutSeconds 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); }