#2 Flatten priority (load levels): run only one job at a time #3

Open
daniel wants to merge 7 commits from feature/#2-flatten-priority-load-levels into develop
pull from: feature/#2-flatten-priority-load-levels
20 changed files with 250 additions and 543 deletions
Showing only changes of commit 4abc94f681 - Show all commits

No files matched your search

+6 -5
View File
@@ -16,6 +16,9 @@ Guidance for AI coding agents working in `zag`, the Zig port of the
- Keep CLI flags, JSON/XML output field order, config defaults and the on-disk job
directory layout compatible with barn (`zag` replaces `barn` in names and paths).
- Port specs from barn's unit tests alongside each module (`test` blocks).
- **Intentional deviation (issue #2)**: zag runs only one job at a time (strict FIFO);
barn's load levels are gone. Old `[load_levels]` / `max_concurrent_jobs` settings and
`ZAG_LOAD_LEVELS_*` env vars still load, are reported as non-fatal warnings, and ignored.
## Layout
@@ -28,19 +31,17 @@ 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 |
| `src/config.zig` | Config structs, defaults, TOML loading/merging, `ZAG_*` env overrides, validation |
| `src/loadclass.zig` | `.load` whitelist parsing and load-level classifier |
| `src/defaults.zig`, `src/defaults/` | Default `zag.conf` and `*.load` files embedded in the binary |
| `src/config.zig` | Config structs, defaults, TOML loading/merging, `ZAG_*` env overrides, validation, deprecated-setting warnings |
| `src/defaults.zig`, `src/defaults/` | Default `zag.conf` embedded in the binary |
| `src/retry.zig` | Retry decision and backoff/jitter delay |
| `src/proc.zig` | Spawn with log redirection, process-group signals, liveness |
| `src/runner.zig` | Runs one job: heartbeat, timeout, kill, completion, retry |
| `src/recovery.zig` | Startup crash recovery of orphaned running jobs |
| `src/scheduler.zig` | Per-load-level concurrency, thread per job, `killJob` |
| `src/scheduler.zig` | Strict single-job FIFO scheduling, thread per job, `killJob` |
| `src/usage.zig` | `ps`/`nvidia-smi` sampling, `usage.csv`, summaries |
| `src/cleanup.zig` | Automatic and manual (`zag clean`) cleanup planning |
| `src/jobjson.zig` | `Job` JSON (shared by CLI `--output=json` and IPC) |
+16 -39
View File
@@ -172,7 +172,6 @@ There needs to be a zag service in order to run jobs (unless you use `--offline`
|---------------|--------------------------------------------------------|
| `job_id` | the id of the job |
| `state` | `queued`, `running`, `succeeded`, `failed`, `canceled` |
| `load_level` | `HIGH`, `MEDIUM`, or `LOW` (auto-detected or manual) |
| `tag` | user defined string |
| `created_at` | Job creation timestamp |
| `started_at` | Execution start timestamp |
@@ -186,7 +185,7 @@ There needs to be a zag service in order to run jobs (unless you use `--offline`
Users can tag jobs for the purpose of filtering using the `--tag=string` CLI option.
Jobs are automatically assigned a **load level** based on the command being run (see [Load Levels](#load-levels)). You can override this with `--load-level={high|medium|low}`.
Zag runs **one job at a time** (strict FIFO by creation order); there are no load levels.
Developers can use the `--offline` command line option to test how the service behaves (e.g., creating tmp files). This runs the same code as the service but without having to run the service.
@@ -195,8 +194,8 @@ Developers can use the `--offline` command line option to test how the service b
`zag status` gets the status of all jobs found in /tmp.
```
ID STATE LOAD TAG CREATED EXIT PID RETRIES NEXT RETRY
job-6d368040 succeeded medium - 2026-01-22 01:48:46 0 17486 - -
ID STATE TAG CREATED EXIT PID RETRIES NEXT RETRY
job-6d368040 succeeded - 2026-01-22 01:48:46 0 17486 - -
Total: 1 job (1 succeeded)
```
@@ -215,35 +214,11 @@ Total: 1 job (1 succeeded)
---
## Load Levels
## Concurrency
Zag supports **per-level job limits** to allow concurrent execution of different types of jobs. For example, you can run multiple downloads while transcoding without overwhelming the system.
### Load Level Types
| Level | Default Max | Use Case |
|-------|-------------|----------|
| HIGH | 2 | CPU/GPU intensive (transcoding, encoding) |
| MEDIUM | 8 | General purpose commands |
| LOW | 32 | Network/IO intensive (downloads, uploads) |
### Auto-Classification
Jobs are automatically classified based on whitelist files in `/etc/zag/`:
- `high.load` - ffmpeg, ffprobe, handbrake, x264, x265, etc.
- `medium.load` - general commands (default if not matched)
- `low.load` - curl, wget, rclone, rsync, aria2c, etc.
### Manual Override
```bash
# Run ffmpeg as LOW load (bypass normal HIGH classification)
zag run --load-level=low -- ffmpeg -i input.mp4 output.mp4
# Run curl as HIGH load (override normal LOW classification)
zag run --load-level=high -- curl -O https://example.com/file.zip
```
Zag runs **one job at a time**: jobs execute strictly in FIFO order by creation time. There
are no load levels, per-level limits, or `--load-level` override (barn had these; zag
intentionally does not — see [Migration from barn](#migration-from-barn)).
---
@@ -255,12 +230,11 @@ zag run --load-level=high -- curl -O https://example.com/file.zip
| Binary | `barn` | `zag` |
| Data dir | `/tmp/barn` | `/tmp/zag` |
| Config | `/etc/barn/barn.conf`, `~/.config/barn/barn.conf` | `/etc/zag/zag.conf`, `~/.config/zag/zag.conf` |
| Environment overrides | `BARN_<SECTION>_<KEY>` | `ZAG_<SECTION>_<KEY>` (`ZAG_LOAD_LEVELS_MAX_HIGH_JOBS` works) |
| Environment overrides | `BARN_<SECTION>_<KEY>` | `ZAG_<SECTION>_<KEY>` (deprecated load-level variables are detected, warned about, and ignored) |
| Socket | `<base>/barn.sock` | `<base>/zag.sock` (mode 0600) |
The CLI surface, `--output={json|xml}` formats, job states, load levels and the on-disk job
layout match barn. Where barn's code disagreed with its own documentation, zag follows the
documentation:
The CLI surface, `--output={json|xml}` formats, job states and the on-disk job layout match
barn. Where barn's code disagreed with its own documentation, zag follows the documentation:
- `zag clean` behaves the same offline and through the service: with none of `--all`,
`--older-than` or `--job-id` it removes nothing.
@@ -273,9 +247,12 @@ documentation:
used consistently by the daemon *and* the CLI.
- Jobs run in their own process group, so `kill` and `service stop --force` take down the whole
process tree. Job directories are created and deleted atomically.
- Without `config install`, the built-in `.load` lists still classify `ffmpeg` as HIGH and
`curl` as LOW.
- `config show` calls the load-limit section `load_levels`, matching the config file.
- Zag runs **one job at a time** (strict FIFO); barn's load levels (high/medium/low
classification, per-level limits, `--load-level`, the `loadLevel` JSON/XML field and the
`LOAD` column of `zag status`) do not exist.
- Old configs and environments still load fine: `[load_levels]`, `max_concurrent_jobs`,
`ZAG_LOAD_LEVELS_*` and `ZAG_SERVICE_MAX_CONCURRENT_JOBS` are detected, reported as
non-fatal warnings, and ignored.
Not implemented: Windows (dropped on purpose), `max_disk_usage_gb`, `preserve_work_dir`, auto-update.
+7 -2
View File
@@ -36,6 +36,8 @@ pub const Context = struct {
config_value: config.Config = .{},
config_error: ?config.Error = null,
config_diag: config.Diagnostic = .{},
/// Deprecation warnings collected while loading the config; printed once per process.
config_deprecations: std.ArrayList([]const u8) = .empty,
pub fn flag(self: *const Context, name: []const u8) bool {
return self.parsed.flag(name);
@@ -71,8 +73,11 @@ pub const Context = struct {
fn loadConfigOnce(self: *Context) void {
if (self.config_loaded) return;
self.config_loaded = true;
if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag)) |c| {
if (config.load(self.arena, self.io, self.env, .{ .explicit_path = self.value("config") }, &self.config_diag, &self.config_deprecations)) |c| {
self.config_value = c;
for (self.config_deprecations.items) |w| {
self.stderr.print("warning: {s}\n", .{w}) catch {};
}
} else |err| {
self.config_error = err;
}
@@ -423,7 +428,7 @@ test "per-command help" {
defer arena.deinit();
const r = try runCaptured(arena.allocator(), &.{ "run", "--help" }, null);
try std.testing.expectEqual(exit_ok, r.code);
try std.testing.expect(std.mem.indexOf(u8, r.out, "--load-level") != null);
try std.testing.expect(std.mem.indexOf(u8, r.out, "--tag") != null);
const s = try runCaptured(arena.allocator(), &.{ "service", "--help" }, null);
try std.testing.expect(std.mem.indexOf(u8, s.out, "restart") != null);
}
+51 -45
View File
@@ -21,7 +21,6 @@ const proc = @import("proc.zig");
const timestamp = @import("timestamp.zig");
const Repository = @import("repository.zig").Repository;
const state_mod = @import("state.zig");
const Classifier = @import("loadclass.zig").Classifier;
const jsonpretty = @import("jsonpretty.zig");
const servicemgr = @import("servicemgr.zig");
@@ -57,7 +56,7 @@ const ReloadState = struct {
fn reloadConfig(ctx_ptr: ?*anyopaque, arena: Allocator) anyerror!config.Config {
const st: *const ReloadState = @ptrCast(@alignCast(ctx_ptr.?));
return config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null);
return config.load(arena, st.io, st.env, .{ .explicit_path = st.explicit_path }, null, null);
}
fn startBackground(ctx: *Context) !u8 {
@@ -125,14 +124,11 @@ pub fn cmdServiceStart(ctx: *Context) !u8 {
}
logging.setFromConfig(cfg.service.log_level);
const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env);
const classifier = try Classifier.loadOrDefaults(ctx.arena, ctx.io, sys_dir);
const reload_state = try ctx.arena.create(ReloadState);
reload_state.* = .{ .io = ctx.io, .env = ctx.env, .explicit_path = ctx.value("config") };
var svc = service_mod.Service.init(ctx.gpa, ctx.io, &dirs, .{
.config = cfg,
.classifier = classifier,
.reload_fn = reloadConfig,
.reload_ctx = reload_state,
});
@@ -554,11 +550,10 @@ pub const config_show_usage =
\\
;
fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8) !Node {
fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8, warnings: []const []const u8) !Node {
var root = MapBuilder.init(arena);
var s = MapBuilder.init(arena);
try s.put("log_level", Node.str(@tagName(cfg.service.log_level)));
try s.put("max_concurrent_jobs", Node.num(cfg.service.max_concurrent_jobs));
try s.put("heartbeat_interval_seconds", Node.num(cfg.service.heartbeat_interval_seconds));
try s.put("ipc_socket", Node.str(socket));
try s.put("stale_heartbeat_threshold_seconds", Node.num(cfg.service.stale_heartbeat_threshold_seconds));
@@ -588,11 +583,11 @@ fn configNode(arena: Allocator, cfg: config.Config, socket: []const u8) !Node {
try st.put("preserve_work_dir", .{ .boolean = cfg.storage.preserve_work_dir });
try root.put("storage", try st.done());
var l = MapBuilder.init(arena);
try l.put("max_high_jobs", Node.num(cfg.load_levels.max_high_jobs));
try l.put("max_medium_jobs", Node.num(cfg.load_levels.max_medium_jobs));
try l.put("max_low_jobs", Node.num(cfg.load_levels.max_low_jobs));
try root.put("load_levels", try l.done());
if (warnings.len > 0) {
const wn = try arena.alloc(Node, warnings.len);
for (warnings, wn) |msg, *n| n.* = Node.str(msg);
try root.put("warnings", .{ .list = wn });
}
return root.done();
}
@@ -602,7 +597,7 @@ pub fn cmdConfigShow(ctx: *Context) !u8 {
const socket = if (show_defaults) try (config.Config{}).ipcSocketPath(ctx.arena) else try cfg.ipcSocketPath(ctx.arena);
if (ctx.format != .human) {
try ctx.emit(try configNode(ctx.arena, cfg, socket));
try ctx.emit(try configNode(ctx.arena, cfg, socket, ctx.config_deprecations.items));
return exit_ok;
}
@@ -621,8 +616,8 @@ pub fn cmdConfigShow(ctx: *Context) !u8 {
try w.print("Config file: {s}\n", .{try std.mem.join(ctx.arena, ", ", found.items)});
}
}
try w.print("\n[service]\nlog_level = {s}\nmax_concurrent_jobs = {d}\nheartbeat_interval_seconds = {d}\nipc_socket = {s}\nstale_heartbeat_threshold_seconds = {d}\n", .{
@tagName(cfg.service.log_level), cfg.service.max_concurrent_jobs, cfg.service.heartbeat_interval_seconds, socket, cfg.service.stale_heartbeat_threshold_seconds,
try w.print("\n[service]\nlog_level = {s}\nheartbeat_interval_seconds = {d}\nipc_socket = {s}\nstale_heartbeat_threshold_seconds = {d}\n", .{
@tagName(cfg.service.log_level), cfg.service.heartbeat_interval_seconds, socket, cfg.service.stale_heartbeat_threshold_seconds,
});
try w.print("\n[jobs]\ndefault_timeout_seconds = {d}\nmax_retries = {d}\nretry_delay_seconds = {d}\nretry_backoff_multiplier = {d:.1}\nretry_on_exit_codes = [", .{
cfg.jobs.default_timeout_seconds, cfg.jobs.max_retries, cfg.jobs.retry_delay_seconds, cfg.jobs.retry_backoff_multiplier,
@@ -635,9 +630,6 @@ pub fn cmdConfigShow(ctx: *Context) !u8 {
try w.print("\n[storage]\nbase_dir = {s}\nmax_disk_usage_gb = {d}\npreserve_work_dir = {any}\n", .{
cfg.storage.base_dir, cfg.storage.max_disk_usage_gb, cfg.storage.preserve_work_dir,
});
try w.print("\n[load_levels]\nmax_high_jobs = {d}\nmax_medium_jobs = {d}\nmax_low_jobs = {d}\n", .{
cfg.load_levels.max_high_jobs, cfg.load_levels.max_medium_jobs, cfg.load_levels.max_low_jobs,
});
return exit_ok;
}
@@ -647,6 +639,7 @@ pub const config_validate_usage =
\\Usage: zag config validate --file <path>
\\
\\Check a configuration file for syntax errors, unknown sections or keys, and bad values.
\\Deprecated settings are reported as warnings and do not affect the exit code.
\\Exits 1 if anything is wrong.
\\
\\Options:
@@ -676,38 +669,53 @@ pub fn cmdConfigValidate(ctx: *Context) !u8 {
try list.append(a, .{ .section = "", .key = "", .message = try std.fmt.allocPrint(a, "Parse error at line {d}: {s}", .{ td.line, what }) });
}
if (list.items.len == 0) {
if (ctx.format == .human) {
try ctx.stdout.print("Configuration is valid: {s}\n", .{path});
} else {
var m = MapBuilder.init(a);
try m.put("valid", .{ .boolean = true });
try m.put("file", Node.str(path));
try ctx.emit(try m.done());
}
return exit_ok;
var error_count: usize = 0;
for (list.items) |p| {
if (!p.is_warning) error_count += 1;
}
const warnings = try problemNodes(a, list.items, true);
const errors = try problemNodes(a, list.items, false);
if (ctx.format == .human) {
try ctx.stdout.print("Configuration errors in {s}:\n\n", .{path});
for (list.items) |p| {
if (p.key.len > 0) try ctx.stdout.print(" Key '{s}': {s}\n", .{ p.key, p.message }) else try ctx.stdout.print(" {s}\n", .{p.message});
for (list.items) |p| if (p.is_warning) try ctx.stdout.print(" Warning: {s}\n", .{p.message});
if (error_count == 0) {
try ctx.stdout.print("Configuration is valid: {s}\n", .{path});
} else {
try ctx.stdout.print("\nConfiguration errors in {s}:\n\n", .{path});
for (list.items) |p| {
if (p.is_warning) continue;
if (p.key.len > 0) try ctx.stdout.print(" Key '{s}': {s}\n", .{ p.key, p.message }) else try ctx.stdout.print(" {s}\n", .{p.message});
}
}
} else {
const nodes = try a.alloc(Node, list.items.len);
for (list.items, nodes) |p, *n| {
var em = MapBuilder.init(a);
if (p.key.len > 0) try em.put("key", Node.str(p.key));
try em.put("message", Node.str(p.message));
n.* = try em.done();
}
var m = MapBuilder.init(a);
try m.put("valid", .{ .boolean = false });
try m.put("valid", .{ .boolean = error_count == 0 });
try m.put("file", Node.str(path));
try m.put("errors", .{ .list = nodes });
if (warnings.len > 0) try m.put("warnings", .{ .list = warnings });
if (error_count > 0) try m.put("errors", .{ .list = errors });
try ctx.emit(try m.done());
}
return exit_error;
return if (error_count == 0) exit_ok else exit_error;
}
/// The JSON node list for the warnings or the errors of a problem list.
fn problemNodes(a: Allocator, list: []const config.Problem, warnings_only: bool) ![]Node {
var count: usize = 0;
for (list) |p| {
if (p.is_warning == warnings_only) count += 1;
}
if (count == 0) return a.alloc(Node, 0);
const nodes = try a.alloc(Node, count);
var i: usize = 0;
for (list) |p| {
if (p.is_warning != warnings_only) continue;
var em = MapBuilder.init(a);
if (p.key.len > 0) try em.put("key", Node.str(p.key));
try em.put("message", Node.str(p.message));
nodes[i] = try em.done();
i += 1;
}
return nodes;
}
fn writeFileCreatingParents(ctx: *Context, path: []const u8, data: []const u8) !void {
@@ -756,8 +764,7 @@ pub const config_install_opts = [_]args_mod.Opt{
pub const config_install_usage =
\\Usage: zag config install [options]
\\
\\Install the default configuration files (zag.conf and the high/medium/low .load
\\whitelists) into the system config directory.
\\Install the default configuration file (zag.conf) into the system config directory.
\\
\\Options:
\\ -d, --directory <dir> Target directory (default: /etc/zag)
@@ -824,7 +831,6 @@ const bash_completion =
\\ case "$prev" in
\\ -o|--output) COMPREPLY=( $(compgen -W "human json xml" -- "$cur") ); return ;;
\\ -s|--state) COMPREPLY=( $(compgen -W "queued running succeeded failed canceled killed" -- "$cur") ); return ;;
\\ -l|--load-level) COMPREPLY=( $(compgen -W "high medium low" -- "$cur") ); return ;;
\\ --config|--barn-dir|-d|--directory|-p|--path|-f|--file) COMPREPLY=( $(compgen -f -- "$cur") ); return ;;
\\ esac
\\ if [[ -z "$cmd" ]]; then
@@ -832,7 +838,7 @@ const bash_completion =
\\ fi
\\ local opts="$global"
\\ case "$cmd" in
\\ run) opts="$opts -t --tag -l --load-level --max-retries --retry-delay --timeout" ;;
\\ run) opts="$opts -t --tag --max-retries --retry-delay --timeout" ;;
\\ status) opts="$opts -t --tag -s --state -n --limit" ;;
\\ describe) opts="$opts --logs --manifest" ;;
\\ usage) opts="$opts -n --limit --csv --summary" ;;
+2 -18
View File
@@ -10,7 +10,6 @@ const Node = output.Node;
const MapBuilder = output.MapBuilder;
const jsonpretty = @import("jsonpretty.zig");
const jobjson = @import("jobjson.zig");
const config = @import("config.zig");
const dirs_mod = @import("dirs.zig");
const Dirs = dirs_mod.Dirs;
const Repository = @import("repository.zig").Repository;
@@ -23,8 +22,6 @@ 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;
@@ -113,7 +110,6 @@ fn summaryNode(arena: Allocator, jobs: []const Job) !Node {
pub const run_opts = [_]args_mod.Opt{
.{ .long = "tag", .short = 't', .takes_value = true },
.{ .long = "load-level", .short = 'l', .takes_value = true },
.{ .long = "max-retries", .takes_value = true },
.{ .long = "retry-delay", .takes_value = true },
.{ .long = "timeout", .takes_value = true },
@@ -127,7 +123,6 @@ pub const run_usage =
\\
\\Options:
\\ -t, --tag <string> Tag for filtering jobs
\\ -l, --load-level <level> high, medium or low (default: auto-detect)
\\ --max-retries <n> Override the maximum number of retries
\\ --retry-delay <secs> Override the initial retry delay
\\ --timeout <secs> Kill the job after this many seconds
@@ -141,9 +136,6 @@ pub fn cmdRun(ctx: *Context) !u8 {
const command = ctx.parsed.positionals;
if (command.len == 0) return ctx.usageError("No command specified", .{});
var load_level: ?LoadLevel = null;
if (ctx.value("load-level")) |l| load_level = LoadLevel.parse(l) orelse
return ctx.usageError("Invalid load level '{s}'. Valid values are: high, medium, low", .{l});
var max_retries: ?u32 = null;
if (ctx.value("max-retries")) |v| max_retries = parseCount(v) orelse return ctx.usageError("Invalid --max-retries '{s}'", .{v});
var retry_delay: ?u32 = null;
@@ -154,7 +146,7 @@ pub fn cmdRun(ctx: *Context) !u8 {
var job: Job = undefined;
if (ctx.flag("offline")) {
job = (try runOffline(ctx, command, load_level, max_retries, retry_delay, timeout)) orelse return exit_error;
job = (try runOffline(ctx, command, max_retries, retry_delay, timeout)) orelse return exit_error;
} else {
var p: Payload = undefined;
p.init(ctx.arena);
@@ -164,7 +156,6 @@ pub fn cmdRun(ctx: *Context) !u8 {
for (command) |c| try p.w.string(c);
try p.w.endArray();
if (ctx.value("tag")) |t| try p.w.field("tag", .string, t);
if (load_level) |l| try p.w.field("loadLevel", .string, l.upper());
if (max_retries) |n| try p.w.field("maxRetries", .int, n);
if (retry_delay) |n| try p.w.field("retryDelaySeconds", .int, n);
if (timeout) |n| try p.w.field("timeoutSeconds", .int, n);
@@ -186,17 +177,14 @@ pub fn cmdRun(ctx: *Context) !u8 {
return exit_ok;
}
fn runOffline(ctx: *Context, command: []const []const u8, load_level: ?LoadLevel, max_retries: ?u32, retry_delay: ?u32, timeout: ?u32) !?Job {
fn runOffline(ctx: *Context, command: []const []const u8, max_retries: ?u32, retry_delay: ?u32, timeout: ?u32) !?Job {
var dirs = try ctx.openDirs();
defer dirs.close(ctx.io);
const repo = Repository.init(ctx.io, &dirs);
const cfg = ctx.configOrDefault();
const sys_dir = try config.systemConfigDir(ctx.arena, ctx.env);
const classifier = try Classifier.loadOrDefaults(ctx.arena, ctx.io, sys_dir);
const created = try repo.create(ctx.arena, command, .{
.tag = ctx.value("tag"),
.load_level = load_level orelse classifier.classify(command),
.max_retries = max_retries orelse cfg.jobs.max_retries,
.retry_delay_seconds = retry_delay orelse cfg.jobs.retry_delay_seconds,
.retry_backoff_multiplier = cfg.jobs.retry_backoff_multiplier,
@@ -308,8 +296,6 @@ fn printStatusTable(ctx: *Context, jobs: []const Job) !void {
try w.writeAll(sep);
try pad(w, "STATE", 9);
try w.writeAll(sep);
try pad(w, "LOAD", 6);
try w.writeAll(sep);
try pad(w, "TAG", tag_w);
try w.writeAll(sep);
try pad(w, "CREATED", 19);
@@ -327,8 +313,6 @@ fn printStatusTable(ctx: *Context, jobs: []const Job) !void {
try w.writeAll(sep);
try colorCell(ctx, j.state.lower(), 9, stateStyle(j.state));
try w.writeAll(sep);
try pad(w, j.load_level.lower(), 6);
try w.writeAll(sep);
try pad(w, j.tag orelse "-", tag_w);
try w.writeAll(sep);
try pad(w, fmtTime(a, j.created_at), 19);
+128 -42
View File
@@ -19,20 +19,12 @@ pub const LogLevel = enum {
pub const Service = struct {
log_level: LogLevel = .info,
/// Deprecated: superseded by `[load_levels]`.
max_concurrent_jobs: u32 = 4,
heartbeat_interval_seconds: u32 = 5,
/// Defaults to `<storage.base_dir>/zag.sock` when unset.
ipc_socket: ?[]const u8 = null,
stale_heartbeat_threshold_seconds: u32 = 30,
};
pub const LoadLevels = struct {
max_high_jobs: u32 = 2,
max_medium_jobs: u32 = 8,
max_low_jobs: u32 = 32,
};
pub const Jobs = struct {
default_timeout_seconds: u32 = 3600,
max_retries: u32 = 3,
@@ -63,7 +55,6 @@ pub const Config = struct {
jobs: Jobs = .{},
cleanup: Cleanup = .{},
storage: Storage = .{},
load_levels: LoadLevels = .{},
/// Socket path: explicit `service.ipc_socket`, else `<base_dir>/zag.sock`.
pub fn ipcSocketPath(self: Config, arena: Allocator) ![]const u8 {
@@ -75,10 +66,6 @@ pub const Config = struct {
const checks = .{
.{ "service", "heartbeat_interval_seconds", self.service.heartbeat_interval_seconds, 1 },
.{ "service", "stale_heartbeat_threshold_seconds", self.service.stale_heartbeat_threshold_seconds, 1 },
.{ "service", "max_concurrent_jobs", self.service.max_concurrent_jobs, 1 },
.{ "load_levels", "max_high_jobs", self.load_levels.max_high_jobs, 1 },
.{ "load_levels", "max_medium_jobs", self.load_levels.max_medium_jobs, 1 },
.{ "load_levels", "max_low_jobs", self.load_levels.max_low_jobs, 1 },
.{ "jobs", "default_timeout_seconds", self.jobs.default_timeout_seconds, 1 },
.{ "cleanup", "max_age_hours", self.cleanup.max_age_hours, 1 },
.{ "cleanup", "cleanup_interval_minutes", self.cleanup.cleanup_interval_minutes, 1 },
@@ -179,7 +166,6 @@ pub fn fromDoc(arena: Allocator, doc: toml.Doc, diag: ?*Diagnostic) Error!Config
try applySection(arena, Jobs, "jobs", doc.get("jobs"), &cfg.jobs, diag);
try applySection(arena, Cleanup, "cleanup", doc.get("cleanup"), &cfg.cleanup, diag);
try applySection(arena, Storage, "storage", doc.get("storage"), &cfg.storage, diag);
try applySection(arena, LoadLevels, "load_levels", doc.get("load_levels"), &cfg.load_levels, diag);
try cfg.validate(diag);
return cfg;
}
@@ -191,9 +177,15 @@ pub const Problem = struct {
/// Empty for problems that concern a whole section.
key: []const u8,
message: []const u8,
/// Non-fatal notice (a deprecated setting); never fails validation.
is_warning: bool = false,
};
const known_sections = [_][]const u8{ "service", "jobs", "cleanup", "storage", "load_levels" };
/// A setting that pre-flattening configs still carry: it loads fine, is ignored, and is
/// reported as a warning (`Problem.is_warning`).
fn isDeprecatedKey(section: []const u8, key: []const u8) bool {
return std.mem.eql(u8, section, "service") and std.mem.eql(u8, key, "max_concurrent_jobs");
}
fn expectation(comptime T: type) []const u8 {
return switch (@typeInfo(T)) {
@@ -229,24 +221,50 @@ fn checkSection(arena: Allocator, comptime T: type, name: []const u8, section: t
}
}
if (!known) {
try out.append(arena, .{
.section = name,
.key = key,
.message = try std.fmt.allocPrint(arena, "Unknown key '{s}' in [{s}] section", .{ key, name }),
});
if (isDeprecatedKey(name, key)) {
try out.append(arena, .{
.section = name,
.key = key,
.message = try std.fmt.allocPrint(arena, "'{s}' is deprecated: only one job runs at a time; remove it from your config", .{key}),
.is_warning = true,
});
} else {
try out.append(arena, .{
.section = name,
.key = key,
.message = try std.fmt.allocPrint(arena, "Unknown key '{s}' in [{s}] section", .{ key, name }),
});
}
}
}
}
/// Everything wrong with a parsed config document: unknown sections and keys, values of the
/// wrong type, and values outside their allowed range.
/// wrong type, and values outside their allowed range. Deprecated settings are reported as
/// warnings and never fail validation.
pub fn problems(arena: Allocator, doc: toml.Doc) Allocator.Error![]const Problem {
var out: std.ArrayList(Problem) = .empty;
var it = doc.iterator();
while (it.next()) |entry| {
const name = entry.key_ptr.*;
const section = entry.value_ptr.*;
if (std.mem.eql(u8, name, "service")) try checkSection(arena, Service, name, section, &out) else if (std.mem.eql(u8, name, "jobs")) try checkSection(arena, Jobs, name, section, &out) else if (std.mem.eql(u8, name, "cleanup")) try checkSection(arena, Cleanup, name, section, &out) else if (std.mem.eql(u8, name, "storage")) try checkSection(arena, Storage, name, section, &out) else if (std.mem.eql(u8, name, "load_levels")) try checkSection(arena, LoadLevels, name, section, &out) else {
if (std.mem.eql(u8, name, "service")) {
try checkSection(arena, Service, name, section, &out);
} else if (std.mem.eql(u8, name, "jobs")) {
try checkSection(arena, Jobs, name, section, &out);
} else if (std.mem.eql(u8, name, "cleanup")) {
try checkSection(arena, Cleanup, name, section, &out);
} else if (std.mem.eql(u8, name, "storage")) {
try checkSection(arena, Storage, name, section, &out);
} else if (std.mem.eql(u8, name, "load_levels")) {
// Kept for compatibility with pre-flattening (and barn) configs.
try out.append(arena, .{
.section = name,
.key = "",
.message = try std.fmt.allocPrint(arena, "[{s}] is deprecated: only one job runs at a time; remove it from your config", .{name}),
.is_warning = true,
});
} else {
try out.append(arena, .{
.section = name,
.key = "",
@@ -287,20 +305,33 @@ pub fn mergeInto(arena: Allocator, dst: *toml.Doc, src: toml.Doc) Allocator.Erro
const env_prefix = "ZAG_";
const env_sections = [_]struct { name: []const u8, canonical: []const u8 }{
.{ .name = "load_levels", .canonical = "load_levels" },
.{ .name = "loadlevels", .canonical = "load_levels" },
.{ .name = "service", .canonical = "service" },
.{ .name = "jobs", .canonical = "jobs" },
.{ .name = "cleanup", .canonical = "cleanup" },
.{ .name = "storage", .canonical = "storage" },
};
/// Applies `ZAG_<SECTION>_<KEY>=value` overrides, e.g. `ZAG_JOBS_MAX_RETRIES=5` or
/// `ZAG_LOAD_LEVELS_MAX_HIGH_JOBS=1`. Values are typed as bool, int, float, else string.
pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map) Allocator.Error!void {
/// `ZAG_LOAD_LEVELS_*`, `ZAG_LOADLEVELS_*` and `ZAG_SERVICE_MAX_CONCURRENT_JOBS` still
/// survive in old service files and shell profiles; `rest` is the name without `ZAG_`.
fn isDeprecatedEnvName(rest: []const u8) bool {
return (rest.len > "load_levels_".len and std.ascii.startsWithIgnoreCase(rest, "load_levels_")) or
(rest.len > "loadlevels_".len and std.ascii.startsWithIgnoreCase(rest, "loadlevels_")) or
std.ascii.eqlIgnoreCase(rest, "service_max_concurrent_jobs");
}
/// Applies `ZAG_<SECTION>_<KEY>=value` overrides, e.g. `ZAG_JOBS_MAX_RETRIES=5`. Values are
/// typed as bool, int, float, else string. Deprecated load-level variables are skipped and,
/// when `deprecations` is non-null, reported there.
pub fn applyEnvironment(arena: Allocator, doc: *toml.Doc, env: *const Environ.Map, deprecations: ?*std.ArrayList([]const u8)) Allocator.Error!void {
for (env.keys(), env.values()) |name, value| {
if (!std.ascii.startsWithIgnoreCase(name, env_prefix)) continue;
const rest = name[env_prefix.len..];
if (isDeprecatedEnvName(rest)) {
if (deprecations) |list| {
try list.append(arena, try std.fmt.allocPrint(arena, "{s} is deprecated: only one job runs at a time; remove it from your environment", .{name}));
}
continue;
}
for (env_sections) |sec| {
if (rest.len <= sec.name.len + 1) continue;
if (!std.ascii.eqlIgnoreCase(rest[0..sec.name.len], sec.name) or rest[sec.name.len] != '_') continue;
@@ -389,8 +420,10 @@ pub const LoadOptions = struct {
};
/// Loads the effective configuration. Unreadable or malformed *implicit* files (system/user)
/// are skipped like barn does; an explicit file that fails to parse is reported.
pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic) Error!Config {
/// are skipped like barn does; an explicit file that fails to parse is reported. When
/// `deprecations` is non-null, removed settings found in the files or the environment are
/// appended to it as warnings.
pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions, diag: ?*Diagnostic, deprecations: ?*std.ArrayList([]const u8)) Error!Config {
var merged: toml.Doc = .empty;
const paths = opts.search_paths orelse try searchPaths(arena, env);
for (paths) |p| {
@@ -403,7 +436,12 @@ pub fn load(arena: Allocator, io: Io, env: *const Environ.Map, opts: LoadOptions
if (opts.explicit_path) |p| {
if (try loadFile(arena, io, p, diag)) |d| try mergeInto(arena, &merged, d);
}
try applyEnvironment(arena, &merged, env);
try applyEnvironment(arena, &merged, env, deprecations);
if (deprecations) |list| {
for (try problems(arena, merged)) |p| {
if (p.is_warning) try list.append(arena, p.message);
}
}
return fromDoc(arena, merged, diag);
}
@@ -420,9 +458,6 @@ test "defaults match barn" {
try std.testing.expectEqual(LogLevel.info, cfg.service.log_level);
try std.testing.expectEqual(@as(u32, 5), cfg.service.heartbeat_interval_seconds);
try std.testing.expectEqual(@as(u32, 30), cfg.service.stale_heartbeat_threshold_seconds);
try std.testing.expectEqual(@as(u32, 2), cfg.load_levels.max_high_jobs);
try std.testing.expectEqual(@as(u32, 8), cfg.load_levels.max_medium_jobs);
try std.testing.expectEqual(@as(u32, 32), cfg.load_levels.max_low_jobs);
try std.testing.expectEqual(@as(u32, 3600), cfg.jobs.default_timeout_seconds);
try std.testing.expectEqual(@as(u32, 3), cfg.jobs.max_retries);
try std.testing.expectEqual(@as(f64, 2.0), cfg.jobs.retry_backoff_multiplier);
@@ -439,7 +474,6 @@ test "embedded default zag.conf parses to the built-in defaults" {
const defaults = @import("defaults.zig");
const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(), defaults.zag_conf), null);
try std.testing.expectEqual((Config{}).jobs.max_retries, cfg.jobs.max_retries);
try std.testing.expectEqual((Config{}).load_levels, cfg.load_levels);
try std.testing.expectEqual((Config{}).cleanup, cfg.cleanup);
try std.testing.expectEqual(@as(usize, 0), cfg.jobs.retry_on_exit_codes.len);
try std.testing.expectEqualStrings("/tmp/zag", cfg.storage.base_dir);
@@ -479,8 +513,6 @@ test "validation rejects bad values and names the key" {
const a = arena.allocator();
var diag: Diagnostic = .{};
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[load_levels]\nmax_high_jobs = 0\n"), &diag));
try std.testing.expectEqualStrings("max_high_jobs", diag.key);
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[jobs]\nretry_backoff_multiplier = 0.5\n"), &diag));
try std.testing.expectEqualStrings("retry_backoff_multiplier", diag.key);
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[service]\nlog_level = \"loud\"\n"), &diag));
@@ -489,7 +521,7 @@ test "validation rejects bad values and names the key" {
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[cleanup]\nenabled = 5\n"), &diag));
}
test "environment overrides, including load_levels" {
test "environment overrides; deprecated load-level vars are warned about and ignored" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
@@ -498,6 +530,7 @@ test "environment overrides, including load_levels" {
try env.put("ZAG_JOBS_MAX_RETRIES", "7");
try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1");
try env.put("ZAG_LOADLEVELS_MAX_LOW_JOBS", "4");
try env.put("ZAG_SERVICE_MAX_CONCURRENT_JOBS", "2");
try env.put("ZAG_CLEANUP_ENABLED", "false");
try env.put("ZAG_SERVICE_LOG_LEVEL", "warn");
try env.put("ZAG_JOBS_RETRY_BACKOFF_MULTIPLIER", "1.5");
@@ -505,11 +538,14 @@ test "environment overrides, including load_levels" {
try env.put("OTHER_JOBS_MAX_RETRIES", "99");
var doc = try testDoc(a, "[jobs]\nmax_retries = 2\n");
try applyEnvironment(a, &doc, &env);
var deprecations: std.ArrayList([]const u8) = .empty;
try applyEnvironment(a, &doc, &env, &deprecations);
try std.testing.expectEqual(@as(usize, 3), deprecations.items.len);
for (deprecations.items) |msg| try std.testing.expect(std.mem.indexOf(u8, msg, "deprecated") != null);
try std.testing.expect(doc.get("load_levels") == null);
const cfg = try fromDoc(a, doc, null);
try std.testing.expectEqual(@as(u32, 7), cfg.jobs.max_retries);
try std.testing.expectEqual(@as(u32, 1), cfg.load_levels.max_high_jobs);
try std.testing.expectEqual(@as(u32, 4), cfg.load_levels.max_low_jobs);
try std.testing.expect(!cfg.cleanup.enabled);
try std.testing.expectEqual(LogLevel.warn, cfg.service.log_level);
try std.testing.expectEqual(@as(f64, 1.5), cfg.jobs.retry_backoff_multiplier);
@@ -542,7 +578,7 @@ test "files merge per key with explicit file and env on top" {
const cfg = try load(a, io, &env, .{
.search_paths = &paths,
.explicit_path = try std.fmt.allocPrint(a, "{s}/explicit.conf", .{base}),
}, null);
}, null, null);
try std.testing.expectEqual(@as(u32, 2), cfg.jobs.max_retries); // user beats system
try std.testing.expectEqual(@as(u32, 99), cfg.jobs.retry_delay_seconds); // env beats files
try std.testing.expectEqual(@as(u32, 20), cfg.cleanup.max_age_hours); // explicit beats system
@@ -551,7 +587,7 @@ test "files merge per key with explicit file and env on top" {
try std.testing.expectError(error.ParseFailed, load(a, io, &env, .{
.search_paths = &.{},
.explicit_path = try std.fmt.allocPrint(a, "{s}/broken.conf", .{base}),
}, &diag));
}, &diag, null));
try std.testing.expectEqual(@as(usize, 1), diag.line);
}
@@ -603,3 +639,53 @@ test "problems reports unknown names, bad types and ranges" {
try std.testing.expectEqual(@as(usize, 1), range.len);
try std.testing.expectEqualStrings("retry_backoff_multiplier", range[0].key);
}
test "deprecated settings warn instead of failing validation" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const ps = try problems(a, try testDoc(a,
\\ [service]
\\ max_concurrent_jobs = 4
\\ [load_levels]
\\ max_high_jobs = 2
));
try std.testing.expectEqual(@as(usize, 2), ps.len);
var saw_section = false;
var saw_key = false;
for (ps) |p| {
try std.testing.expect(p.is_warning);
try std.testing.expect(std.mem.indexOf(u8, p.message, "deprecated") != null);
if (std.mem.eql(u8, p.section, "load_levels")) saw_section = true;
if (std.mem.eql(u8, p.key, "max_concurrent_jobs")) saw_key = true;
}
try std.testing.expect(saw_section and saw_key);
// The deprecated values never make it into the config, and nothing errors.
const cfg = try fromDoc(a, try testDoc(a, "[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n"), null);
try std.testing.expectEqual((Config{}).jobs.max_retries, cfg.jobs.max_retries);
}
test "load reports deprecated settings from files and env" {
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();
try tmp.dir.writeFile(io, .{ .sub_path = "old.conf", .data = "[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n" });
var env = Environ.Map.init(std.testing.allocator);
defer env.deinit();
try env.put("ZAG_LOAD_LEVELS_MAX_HIGH_JOBS", "1");
var deprecations: std.ArrayList([]const u8) = .empty;
const cfg = try load(a, io, &env, .{
.search_paths = &.{try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/old.conf", .{tmp.sub_path})},
}, null, &deprecations);
try std.testing.expectEqual(@as(usize, 3), deprecations.items.len);
for (deprecations.items) |msg| try std.testing.expect(std.mem.indexOf(u8, msg, "deprecated") != null);
try std.testing.expectEqual(LogLevel.info, cfg.service.log_level);
}
-6
View File
@@ -1,15 +1,9 @@
//! Default configuration files embedded in the binary (written by `zag config install`).
pub const zag_conf = @embedFile("defaults/zag.conf");
pub const high_load = @embedFile("defaults/high.load");
pub const medium_load = @embedFile("defaults/medium.load");
pub const low_load = @embedFile("defaults/low.load");
pub const File = struct { name: []const u8, content: []const u8 };
/// Everything `config install` writes into the system config directory.
pub const files = [_]File{
.{ .name = "zag.conf", .content = zag_conf },
.{ .name = "high.load", .content = high_load },
.{ .name = "medium.load", .content = medium_load },
.{ .name = "low.load", .content = low_load },
};
-16
View File
@@ -1,16 +0,0 @@
# High load commands - CPU/GPU intensive (transcoding, encoding)
# Maximum concurrent: 2 (default)
#
# Format:
# - Binary name: ffmpeg (matches any path ending with this executable)
# - Full path: /usr/local/bin/ffmpeg
# - Directory: /opt/encoders/ (trailing slash = match any executable in this directory)
ffmpeg
ffprobe
handbrake
HandBrakeCLI
x264
x265
av1an
svt-av1
-16
View File
@@ -1,16 +0,0 @@
# Low load commands - Network/IO intensive (downloads, uploads)
# Maximum concurrent: 32 (default)
#
# Format:
# - Binary name: curl (matches any path ending with this executable)
# - Full path: /usr/local/bin/rclone
# - Directory: /opt/downloaders/ (trailing slash = match any executable in this directory)
curl
wget
rclone
rsync
aria2c
scp
sftp
cadaver
-4
View File
@@ -1,4 +0,0 @@
# Medium load commands
# Maximum concurrent: 8 (default)
#
# Empty by default - unmatched commands are classified as MEDIUM
+2 -12
View File
@@ -5,8 +5,8 @@
# Logging verbosity: debug, info, warn, error
log_level = "info"
# DEPRECATED: Use [load_levels] section instead
# max_concurrent_jobs = 4
# Zag runs only one job at a time (strict FIFO by creation order);
# concurrency is not configurable.
# How often running jobs update their heartbeat (seconds)
heartbeat_interval_seconds = 5
@@ -14,16 +14,6 @@ heartbeat_interval_seconds = 5
# Heartbeat age before a job is considered orphaned (seconds)
stale_heartbeat_threshold_seconds = 30
[load_levels]
# Maximum concurrent high load jobs (CPU/GPU intensive)
max_high_jobs = 2
# Maximum concurrent medium load jobs (general purpose)
max_medium_jobs = 8
# Maximum concurrent low load jobs (network/IO intensive)
max_low_jobs = 32
[jobs]
# Maximum time a job can run before being killed (seconds)
default_timeout_seconds = 3600
-3
View File
@@ -1,7 +1,6 @@
//! 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;
@@ -30,7 +29,6 @@ pub const Job = struct {
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();
@@ -54,7 +52,6 @@ pub const Manifest = struct {
max_retries: u32 = 0,
retry_delay_seconds: u32 = 30,
retry_backoff_multiplier: f64 = 2.0,
load_level: LoadLevel = .medium,
/// Per-job timeout in seconds; null uses the configured default.
timeout_seconds: ?u32 = null,
+1 -9
View File
@@ -1,12 +1,11 @@
//! JSON representation of a `Job`, shared by `--output=json` and the IPC protocol.
//! Field order matches barn: id, state (UPPERCASE), loadLevel, command, tag, timestamps,
//! Field order matches barn: id, state (UPPERCASE), command, tag, timestamps,
//! exitCode, error, pid, heartbeat, retryCount, retryAt, terminal, running, queued.
const std = @import("std");
const Allocator = std.mem.Allocator;
const jsonpretty = @import("jsonpretty.zig");
const timestamp = @import("timestamp.zig");
const state_mod = @import("state.zig");
const LoadLevel = @import("loadlevel.zig").LoadLevel;
const job_mod = @import("job.zig");
const Job = job_mod.Job;
const Instant = job_mod.Instant;
@@ -33,7 +32,6 @@ pub fn writeJob(w: *jsonpretty.Writer, job: Job) !void {
try w.beginObject();
try w.field("id", .string, job.id);
try w.field("state", .string, upperState(job.state));
try w.field("loadLevel", .string, job.load_level.upper());
try w.key("command");
try w.beginArray();
for (job.command) |arg| try w.string(arg);
@@ -75,7 +73,6 @@ pub fn writeJobs(w: *jsonpretty.Writer, jobs: []const Job) !void {
const RawJob = struct {
id: []const u8,
state: []const u8,
loadLevel: ?[]const u8 = null,
command: []const []const u8,
tag: ?[]const u8 = null,
createdAt: []const u8,
@@ -121,7 +118,6 @@ pub fn jobFromValue(arena: Allocator, value: std.json.Value) ParseError!Job {
.heartbeat = try optInstant(raw.heartbeat),
.retry_count = raw.retryCount,
.retry_at = try optInstant(raw.retryAt),
.load_level = if (raw.loadLevel) |l| LoadLevel.parse(l) orelse return error.InvalidJob else .medium,
};
}
@@ -146,7 +142,6 @@ fn sampleJob() Job {
.exit_code = .{ .code = 0 },
.pid = 17486,
.heartbeat = 1_769_046_527 * std.time.ns_per_s + 161_895_000,
.load_level = .medium,
};
}
@@ -159,7 +154,6 @@ test "job JSON matches barn's field layout" {
\\{
\\ "id" : "job-6d368040",
\\ "state" : "SUCCEEDED",
\\ "loadLevel" : "MEDIUM",
\\ "command" : [ "echo", "Hello World" ],
\\ "tag" : null,
\\ "createdAt" : "2026-01-22T01:48:46.739979Z",
@@ -189,7 +183,6 @@ test "jobs round-trip through compact JSON" {
failed.tag = "t";
failed.retry_count = 2;
failed.retry_at = failed.created_at + std.time.ns_per_s;
failed.load_level = .low;
const jobs = [_]Job{ sampleJob(), failed };
var aw: std.Io.Writer.Allocating = .init(a);
@@ -206,7 +199,6 @@ test "jobs round-trip through compact JSON" {
try std.testing.expectEqualStrings("start_failed", back[1].exit_code.?.symbol);
try std.testing.expectEqualStrings("boom \"quoted\"", back[1].err.?);
try std.testing.expectEqual(@as(u32, 2), back[1].retry_count);
try std.testing.expectEqual(LoadLevel.low, back[1].load_level);
try std.testing.expectEqual(failed.retry_at.?, back[1].retry_at.?);
}
-223
View File
@@ -1,223 +0,0 @@
//! Load-level classification from `high.load`, `medium.load` and `low.load` whitelist files.
//! Each line is a binary name (`ffmpeg`), a full path (`/usr/bin/ffmpeg`) or a directory
//! (`/opt/encoders/`); `#` starts a comment. HIGH is checked first, then MEDIUM, then LOW;
//! unmatched commands are MEDIUM. Port of barn's `LoadLevelClassifier` and `CommandMatcher`.
const std = @import("std");
const Io = std.Io;
const Allocator = std.mem.Allocator;
const LoadLevel = @import("loadlevel.zig").LoadLevel;
pub const Matcher = union(enum) {
/// Matches when the basename of the executable equals the name.
executable_name: []const u8,
/// Matches when the executable path equals this path.
full_path: []const u8,
/// Matches when the executable lives directly in this directory.
directory: []const u8,
pub fn matches(self: Matcher, command: []const []const u8) bool {
if (command.len == 0) return false;
const exe = command[0];
return switch (self) {
.executable_name => |n| std.mem.eql(u8, n, basename(exe)),
.full_path => |p| std.mem.eql(u8, normalize(p), normalize(exe)),
.directory => |d| if (dirname(exe)) |parent|
std.mem.eql(u8, normalize(parent), normalize(d))
else
false,
};
}
};
fn basename(path: []const u8) []const u8 {
const t = std.mem.trimEnd(u8, path, "/");
const i = std.mem.lastIndexOfScalar(u8, t, '/') orelse return t;
return t[i + 1 ..];
}
fn dirname(path: []const u8) ?[]const u8 {
const t = std.mem.trimEnd(u8, path, "/");
const i = std.mem.lastIndexOfScalar(u8, t, '/') orelse return null;
if (i == 0) return "/";
return t[0..i];
}
/// Strips trailing slashes (keeping a lone `/`).
fn normalize(path: []const u8) []const u8 {
if (path.len <= 1) return path;
const t = std.mem.trimEnd(u8, path, "/");
return if (t.len == 0) "/" else t;
}
pub fn parseEntry(entry: []const u8) Matcher {
if (std.mem.endsWith(u8, entry, "/")) return .{ .directory = entry };
if (std.mem.indexOfScalar(u8, entry, '/') != null) return .{ .full_path = entry };
return .{ .executable_name = entry };
}
/// Parses a `.load` file body. Slices point into `text`; the list is allocated from `arena`.
pub fn parseLoadFile(arena: Allocator, text: []const u8) Allocator.Error![]const Matcher {
var list: std.ArrayList(Matcher) = .empty;
var lines = std.mem.splitScalar(u8, text, '\n');
while (lines.next()) |raw| {
const line = std.mem.trim(u8, raw, &std.ascii.whitespace);
if (line.len == 0 or line[0] == '#') continue;
try list.append(arena, parseEntry(line));
}
return list.toOwnedSlice(arena);
}
pub const Classifier = struct {
high: []const Matcher = &.{},
medium: []const Matcher = &.{},
low: []const Matcher = &.{},
pub fn classify(self: Classifier, command: []const []const u8) LoadLevel {
if (command.len == 0) return .default;
for (self.high) |m| if (m.matches(command)) return .high;
for (self.medium) |m| if (m.matches(command)) return .medium;
for (self.low) |m| if (m.matches(command)) return .low;
return .default;
}
/// Loads the three files from `config_dir`; missing or unreadable files count as empty.
pub fn load(arena: Allocator, io: Io, config_dir: []const u8) Allocator.Error!Classifier {
return .{
.high = try loadOne(arena, io, config_dir, "high.load"),
.medium = try loadOne(arena, io, config_dir, "medium.load"),
.low = try loadOne(arena, io, config_dir, "low.load"),
};
}
/// 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");
return .{
.high = try parseLoadFile(arena, defaults.high_load),
.medium = try parseLoadFile(arena, defaults.medium_load),
.low = try parseLoadFile(arena, defaults.low_load),
};
}
};
fn loadOne(arena: Allocator, io: Io, dir: []const u8, name: []const u8) Allocator.Error![]const Matcher {
const path = try std.fmt.allocPrint(arena, "{s}/{s}", .{ dir, name });
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| switch (err) {
error.OutOfMemory => return error.OutOfMemory,
else => return &.{},
};
return parseLoadFile(arena, text);
}
fn cmd(comptime args: []const []const u8) []const []const u8 {
return args;
}
test "entry kinds" {
try std.testing.expectEqualStrings("ffmpeg", parseEntry("ffmpeg").executable_name);
try std.testing.expectEqualStrings("/usr/bin/ffmpeg", parseEntry("/usr/bin/ffmpeg").full_path);
try std.testing.expectEqualStrings("/opt/encoders/", parseEntry("/opt/encoders/").directory);
}
test "executable name matches any path ending with it" {
const m = parseEntry("ffmpeg");
try std.testing.expect(m.matches(cmd(&.{ "ffmpeg", "-i", "x" })));
try std.testing.expect(m.matches(cmd(&.{"/usr/local/bin/ffmpeg"})));
try std.testing.expect(!m.matches(cmd(&.{"ffmpeg2"})));
try std.testing.expect(!m.matches(cmd(&.{ "echo", "ffmpeg" })));
try std.testing.expect(!m.matches(&.{}));
}
test "full path and directory matching" {
const fp = parseEntry("/usr/local/bin/rclone");
try std.testing.expect(fp.matches(cmd(&.{ "/usr/local/bin/rclone", "copy" })));
try std.testing.expect(!fp.matches(cmd(&.{"rclone"})));
try std.testing.expect(!fp.matches(cmd(&.{"/usr/bin/rclone"})));
const d = parseEntry("/opt/encoders/");
try std.testing.expect(d.matches(cmd(&.{"/opt/encoders/x265"})));
try std.testing.expect(d.matches(cmd(&.{"/opt/encoders//x265"})));
try std.testing.expect(!d.matches(cmd(&.{"/opt/encoders/sub/x265"})));
try std.testing.expect(!d.matches(cmd(&.{"x265"})));
}
test "load files skip comments and blanks" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const ms = try parseLoadFile(arena.allocator(), "# c\n\n ffmpeg \n/opt/x/\n # more\ncurl\n");
try std.testing.expectEqual(@as(usize, 3), ms.len);
}
test "priority is high, then medium, then low, default medium" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const c: Classifier = .{
.high = try parseLoadFile(a, "ffmpeg\n"),
.medium = try parseLoadFile(a, "both\n"),
.low = try parseLoadFile(a, "curl\nboth\nffmpeg\n"),
};
try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"ffmpeg"})));
try std.testing.expectEqual(LoadLevel.low, c.classify(cmd(&.{"curl"})));
try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{"both"})));
try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{"echo"})));
try std.testing.expectEqual(LoadLevel.medium, c.classify(&.{}));
}
test "embedded defaults classify ffmpeg high and curl low" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const c = try Classifier.fromDefaults(arena.allocator());
try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{ "ffprobe", "-i", "x" })));
try std.testing.expectEqual(LoadLevel.high, c.classify(cmd(&.{"/usr/bin/HandBrakeCLI"})));
try std.testing.expectEqual(LoadLevel.low, c.classify(cmd(&.{ "curl", "-O", "u" })));
try std.testing.expectEqual(LoadLevel.medium, c.classify(cmd(&.{ "echo", "hi" })));
}
test "load reads files from a directory and tolerates missing ones" {
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();
try tmp.dir.writeFile(io, .{ .sub_path = "high.load", .data = "mytool\n" });
const dir = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path});
const c = try Classifier.load(a, io, dir);
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"})));
}
-56
View File
@@ -1,56 +0,0 @@
//! 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);
}
-2
View File
@@ -196,7 +196,6 @@ fn xmlJob(out: *Io.Writer, job: Job, depth: usize) !void {
if (job.heartbeat) |t| try xmlJobTime(out, d, "heartbeat", t);
if (job.retry_count > 0) try xmlLeaf(out, d, "retry_count", "{d}", .{job.retry_count});
if (job.retry_at) |t| try xmlJobTime(out, d, "retry_at", t);
try xmlLeaf(out, d, "load_level", "{s}", .{job.load_level.lower()});
try indent(out, depth);
try out.writeAll("</job>\n");
}
@@ -522,7 +521,6 @@ test "XML job follows barn's element shape" {
\\ <created_at>2026-01-22T01:48:46Z</created_at>
\\ <exit_code>0</exit_code>
\\ <pid>17486</pid>
\\ <load_level>medium</load_level>
\\</job>
\\
);
+12 -17
View File
@@ -9,7 +9,6 @@ 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;
@@ -26,7 +25,6 @@ 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,
@@ -66,7 +64,6 @@ pub const Repository = struct {
.max_retries = opts.max_retries,
.retry_delay_seconds = opts.retry_delay_seconds,
.retry_backoff_multiplier = opts.retry_backoff_multiplier,
.load_level = opts.load_level,
.timeout_seconds = opts.timeout_seconds,
};
try manifest.validate();
@@ -93,7 +90,6 @@ pub const Repository = struct {
.command = command,
.tag = opts.tag,
.created_at = manifest.created_at,
.load_level = opts.load_level,
};
}
@@ -159,7 +155,6 @@ pub const Repository = struct {
.heartbeat = try sf.readHeartbeat(),
.retry_count = (try sf.readRetryCount()) orelse 0,
.retry_at = try sf.readRetryAt(),
.load_level = manifest.load_level,
};
}
@@ -299,7 +294,6 @@ pub fn writeManifestJson(out: *Io.Writer, m: Manifest) !void {
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());
if (m.timeout_seconds) |t| try w.field("timeoutSeconds", .int, t);
try w.endObject();
}
@@ -312,11 +306,11 @@ const RawManifest = struct {
maxRetries: u32 = 0,
retryDelaySeconds: u32 = 30,
retryBackoffMultiplier: f64 = 2.0,
loadLevel: ?[]const u8 = null,
timeoutSeconds: ?u32 = null,
};
/// Parses a barn- or zag-written `manifest.json`. A missing `loadLevel` defaults to MEDIUM.
/// Parses a barn- or zag-written `manifest.json`; unknown fields (e.g. barn's `loadLevel`)
/// are ignored.
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;
@@ -328,7 +322,6 @@ pub fn parseManifestJson(arena: Allocator, text: []const u8) !Manifest {
.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,
.timeout_seconds = raw.timeoutSeconds,
};
m.validate() catch return error.InvalidManifest;
@@ -373,7 +366,6 @@ test "manifest JSON matches barn's layout and round-trips" {
.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);
@@ -385,25 +377,22 @@ test "manifest JSON matches barn's layout and round-trips" {
\\ "createdAt" : "2026-01-22T01:48:46Z",
\\ "maxRetries" : 3,
\\ "retryDelaySeconds" : 30,
\\ "retryBackoffMultiplier" : 2.0,
\\ "loadLevel" : "HIGH"
\\ "retryBackoffMultiplier" : 2.0
\\}
, 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" {
test "manifest without optional fields (older barn jobs) still parses" {
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(),
@@ -411,18 +400,24 @@ test "manifest without loadLevel (older barn jobs) defaults to medium" {
));
}
test "manifest with unknown loadLevel field (upgraded from older zag) still parses" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const m = try parseManifestJson(arena.allocator(), "{\"id\":\"job-2\",\"command\":[\"ls\"],\"createdAt\":\"2026-01-22T01:48:46.749629Z\",\"loadLevel\":\"HIGH\"}");
try std.testing.expectEqualStrings("job-2", m.id);
}
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 });
const created = try env.repo().create(a, &.{ "echo", "hi" }, .{ .tag = "downloading" });
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]);
-2
View File
@@ -13,14 +13,12 @@ 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");
pub const defaults = @import("defaults.zig");
pub const config = @import("config.zig");
pub const loadclass = @import("loadclass.zig");
pub const retry = @import("retry.zig");
pub const proc = @import("proc.zig");
pub const runner = @import("runner.zig");
+7 -22
View File
@@ -23,8 +23,6 @@ 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;
@@ -32,7 +30,6 @@ pub const ReloadFn = *const fn (ctx: ?*anyopaque, arena: Allocator) anyerror!con
pub const Options = struct {
config: config.Config = .{},
classifier: Classifier = .{},
reload_fn: ?ReloadFn = null,
reload_ctx: ?*anyopaque = null,
scheduler_tick_ms: u64 = 1_000,
@@ -308,11 +305,6 @@ pub const Service = struct {
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);
}
@@ -453,22 +445,15 @@ test "run a job end to end over IPC" {
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 } } });
test "unknown loadLevel in a run_job payload is ignored" {
const h = try Harness.create(.{});
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);
// Old clients (and pre-#2 zag) may still send a loadLevel; it is ignored, not an error.
const job = try h.okObj("run_job", "{\"command\":[\"echo\",\"x\"],\"loadLevel\":\"high\"}");
try std.testing.expectEqualStrings("QUEUED", job.get("state").?.string);
try std.testing.expect(job.get("loadLevel") == null);
try h.waitState(job.get("id").?.string, "SUCCEEDED");
}
test "request validation and not-found errors" {
+18 -4
View File
@@ -17,9 +17,11 @@ contains() { # contains <name> <needle> <haystack>
}
json_field() { printf '%s\n' "$2" | sed -n "s/.*\"$1\" : \"\{0,1\}\([^\",]*\)\"\{0,1\},\{0,1\}\$/\1/p" | head -1; }
wait_state() { # wait_state <id> <state> [seconds]
local i
# ${2,,} would work on bash >= 4, but macOS ships bash 3.2
local lower i
lower=$(printf '%s' "$2" | tr '[:upper:]' '[:lower:]')
for ((i = 0; i < ${3:-100}; i++)); do
[[ $(json_field state "$(Z describe -o json "$1" --offline)") == "${2,,}" ]] && return 0
[[ $(json_field state "$(Z describe -o json "$1" --offline)") == "$lower" ]] && return 0
sleep 0.1
done
return 1
@@ -48,12 +50,15 @@ contains "clean --all removes it" "Cleaned 1 job" "$(Z clean --offline --all)"
contains "status empty" "No jobs found." "$(Z status --offline)"
# --- config -----------------------------------------------------------------------------
contains "config show --defaults" "max_high_jobs = 2" "$(Z config show --defaults)"
contains "config show --defaults" "retry_backoff_multiplier = 2.0" "$(Z config show --defaults)"
printf '[jobs]\nmax_retries = 0\nbogus = 1\n' >"$DIR/bad.conf"
Z config validate --file "$DIR/bad.conf" >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "validate flags bad config" || fail "validate flags bad config"
printf '[jobs]\nmax_retries = 0\n' >"$DIR/good.conf"
contains "validate accepts good config" "Configuration is valid" "$(Z config validate --file "$DIR/good.conf")"
contains "install --show prints files" "high.load" "$(Z config install --show)"
printf '[service]\nmax_concurrent_jobs = 4\n[load_levels]\nmax_high_jobs = 2\n' >"$DIR/deprecated.conf"
deprecated_out=$(Z config validate --file "$DIR/deprecated.conf" 2>&1); rc=$?
[[ $rc -eq 0 ]] && contains "validate warns on deprecated settings, exit 0" "deprecated" "$deprecated_out" || fail "validate warns on deprecated settings (rc=$rc)"
contains "install --show prints files" "zag.conf" "$(Z config install --show)"
# --- daemon -----------------------------------------------------------------------------
Z run echo hi >/dev/null 2>&1; [[ $? -eq 1 ]] && pass "run without service exits 1" || fail "run without service exits 1"
@@ -82,6 +87,15 @@ out=$(Z run -o json --timeout 1 sleep 30); tid=$(json_field id "$out")
sleep 3
contains "timeout fails the job" '"exitCode" : "timeout"' "$(Z describe -o json "$tid" --offline)"
# Strict single-job FIFO: while the first job runs, the second stays queued, and both
# finish in creation order.
out=$(Z run -o json sleep 3); a1=$(json_field id "$out")
wait_state "$a1" RUNNING && pass "serial: first job is running" || fail "serial: first job is running"
out=$(Z run -o json sleep 1); b1=$(json_field id "$out")
contains "serial: second job stays queued" '"state" : "QUEUED"' "$out"
wait_state "$a1" SUCCEEDED && pass "serial: first job finishes first" || fail "serial: first job finishes first"
wait_state "$b1" SUCCEEDED && pass "serial: second job finishes second" || fail "serial: second job finishes second"
contains "service reload" "Configuration reloaded" "$(Z service reload)"
contains "clean via IPC" "Cleaned" "$(Z clean --all --include-failed)"
contains "service stop" "Zag service stopped" "$(Z service stop)"