feat: M2 configuration and load-level classification
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
e39e1c91a4
commit
779ca1af83
9 files changed
+792
No files matched your search
@@ -33,3 +33,6 @@ Guidance for AI coding agents working in `zag`, the Zig port of the
|
||||
| `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 |
|
||||
+479
@@ -0,0 +1,479 @@
|
||||
//! Configuration: defaults, TOML file loading, `ZAG_<SECTION>_<KEY>` environment overrides
|
||||
//! and validation. Port of barn's `ConfigLoader` and `*Config` records.
|
||||
//!
|
||||
//! Precedence (lowest to highest): built-in defaults, system file, user file, explicit
|
||||
//! `--config` file, environment. Files merge per key.
|
||||
const std = @import("std");
|
||||
const builtin = @import("builtin");
|
||||
const Io = std.Io;
|
||||
const Allocator = std.mem.Allocator;
|
||||
const Environ = std.process.Environ;
|
||||
const toml = @import("toml.zig");
|
||||
|
||||
pub const LogLevel = enum {
|
||||
debug,
|
||||
info,
|
||||
warn,
|
||||
@"error",
|
||||
};
|
||||
|
||||
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,
|
||||
retry_delay_seconds: u32 = 30,
|
||||
retry_backoff_multiplier: f64 = 2.0,
|
||||
/// Empty means every non-zero exit code is retryable.
|
||||
retry_on_exit_codes: []const i32 = &.{},
|
||||
};
|
||||
|
||||
pub const Cleanup = struct {
|
||||
enabled: bool = true,
|
||||
max_age_hours: u32 = 72,
|
||||
cleanup_interval_minutes: u32 = 60,
|
||||
keep_failed_jobs: bool = true,
|
||||
keep_failed_jobs_hours: u32 = 168,
|
||||
};
|
||||
|
||||
pub const Storage = struct {
|
||||
base_dir: []const u8 = default_base_dir,
|
||||
max_disk_usage_gb: u32 = 50,
|
||||
preserve_work_dir: bool = false,
|
||||
};
|
||||
|
||||
pub const default_base_dir = if (builtin.os.tag == .windows) "%TEMP%\\zag" else "/tmp/zag";
|
||||
|
||||
pub const Config = struct {
|
||||
service: Service = .{},
|
||||
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 {
|
||||
if (self.service.ipc_socket) |p| return p;
|
||||
return std.fmt.allocPrint(arena, "{s}/zag.sock", .{self.storage.base_dir});
|
||||
}
|
||||
|
||||
pub fn validate(self: Config, diag: ?*Diagnostic) Error!void {
|
||||
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 },
|
||||
.{ "cleanup", "keep_failed_jobs_hours", self.cleanup.keep_failed_jobs_hours, 1 },
|
||||
.{ "storage", "max_disk_usage_gb", self.storage.max_disk_usage_gb, 1 },
|
||||
};
|
||||
inline for (checks) |c| {
|
||||
if (c[2] < c[3]) return fail(diag, c[0], c[1], error.OutOfRange);
|
||||
}
|
||||
if (self.jobs.retry_backoff_multiplier < 1.0)
|
||||
return fail(diag, "jobs", "retry_backoff_multiplier", error.OutOfRange);
|
||||
if (self.storage.base_dir.len == 0) return fail(diag, "storage", "base_dir", error.OutOfRange);
|
||||
}
|
||||
};
|
||||
|
||||
pub const Error = error{ InvalidValue, OutOfRange, ParseFailed, ReadFailed, OutOfMemory };
|
||||
|
||||
/// Describes what went wrong; strings are static or borrowed from the loaded document.
|
||||
pub const Diagnostic = struct {
|
||||
section: []const u8 = "",
|
||||
key: []const u8 = "",
|
||||
/// Set for `ParseFailed`: the file and 1-based line.
|
||||
path: []const u8 = "",
|
||||
line: usize = 0,
|
||||
};
|
||||
|
||||
fn fail(diag: ?*Diagnostic, section: []const u8, key: []const u8, err: Error) Error {
|
||||
if (diag) |d| {
|
||||
d.section = section;
|
||||
d.key = key;
|
||||
}
|
||||
return err;
|
||||
}
|
||||
|
||||
// -- value conversion ------------------------------------------------------------------
|
||||
|
||||
fn convert(arena: Allocator, comptime T: type, v: toml.Value) Error!T {
|
||||
switch (@typeInfo(T)) {
|
||||
.optional => |o| return try convert(arena, o.child, v),
|
||||
.bool => return switch (v) {
|
||||
.boolean => |b| b,
|
||||
.string => |s| if (std.ascii.eqlIgnoreCase(s, "true")) true else if (std.ascii.eqlIgnoreCase(s, "false")) false else error.InvalidValue,
|
||||
else => error.InvalidValue,
|
||||
},
|
||||
.int => return switch (v) {
|
||||
.int => |n| std.math.cast(T, n) orelse error.OutOfRange,
|
||||
.float => |f| std.math.cast(T, @as(i64, @intFromFloat(f))) orelse error.OutOfRange,
|
||||
.string => |s| std.fmt.parseInt(T, s, 10) catch error.InvalidValue,
|
||||
else => error.InvalidValue,
|
||||
},
|
||||
.float => return switch (v) {
|
||||
.float => |f| f,
|
||||
.int => |n| @floatFromInt(n),
|
||||
.string => |s| std.fmt.parseFloat(T, s) catch error.InvalidValue,
|
||||
else => error.InvalidValue,
|
||||
},
|
||||
.@"enum" => {
|
||||
const s = switch (v) {
|
||||
.string => |s| s,
|
||||
else => return error.InvalidValue,
|
||||
};
|
||||
inline for (@typeInfo(T).@"enum".fields) |f| {
|
||||
if (std.ascii.eqlIgnoreCase(s, f.name)) return @field(T, f.name);
|
||||
}
|
||||
return error.InvalidValue;
|
||||
},
|
||||
.pointer => |p| {
|
||||
if (p.size != .slice) @compileError("unsupported config type " ++ @typeName(T));
|
||||
if (p.child == u8) return switch (v) {
|
||||
.string => |s| s,
|
||||
else => error.InvalidValue,
|
||||
};
|
||||
const arr = switch (v) {
|
||||
.array => |a| a,
|
||||
else => return error.InvalidValue,
|
||||
};
|
||||
const out = try arena.alloc(p.child, arr.len);
|
||||
for (arr, out) |item, *slot| slot.* = try convert(arena, p.child, item);
|
||||
return out;
|
||||
},
|
||||
else => @compileError("unsupported config type " ++ @typeName(T)),
|
||||
}
|
||||
}
|
||||
|
||||
fn applySection(arena: Allocator, comptime T: type, name: []const u8, section: ?toml.Section, out: *T, diag: ?*Diagnostic) Error!void {
|
||||
const s = section orelse return;
|
||||
inline for (@typeInfo(T).@"struct".fields) |f| {
|
||||
if (s.get(f.name)) |v| {
|
||||
@field(out, f.name) = convert(arena, f.type, v) catch |err| return fail(diag, name, f.name, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds a `Config` from a merged TOML document (unknown sections/keys are ignored).
|
||||
pub fn fromDoc(arena: Allocator, doc: toml.Doc, diag: ?*Diagnostic) Error!Config {
|
||||
var cfg: Config = .{};
|
||||
try applySection(arena, Service, "service", doc.get("service"), &cfg.service, diag);
|
||||
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;
|
||||
}
|
||||
|
||||
// -- merging ---------------------------------------------------------------------------
|
||||
|
||||
/// Copies every key of `src` into `dst`, overriding existing keys.
|
||||
pub fn mergeInto(arena: Allocator, dst: *toml.Doc, src: toml.Doc) Allocator.Error!void {
|
||||
var it = src.iterator();
|
||||
while (it.next()) |entry| {
|
||||
const gop = try dst.getOrPut(arena, entry.key_ptr.*);
|
||||
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
||||
var kit = entry.value_ptr.iterator();
|
||||
while (kit.next()) |kv| try gop.value_ptr.put(arena, kv.key_ptr.*, kv.value_ptr.*);
|
||||
}
|
||||
}
|
||||
|
||||
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 {
|
||||
for (env.keys(), env.values()) |name, value| {
|
||||
if (!std.ascii.startsWithIgnoreCase(name, env_prefix)) continue;
|
||||
const rest = name[env_prefix.len..];
|
||||
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;
|
||||
const key = try std.ascii.allocLowerString(arena, rest[sec.name.len + 1 ..]);
|
||||
const gop = try doc.getOrPut(arena, sec.canonical);
|
||||
if (!gop.found_existing) gop.value_ptr.* = .empty;
|
||||
try gop.value_ptr.put(arena, key, try parseEnvValue(arena, value));
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn parseEnvValue(arena: Allocator, text: []const u8) Allocator.Error!toml.Value {
|
||||
if (std.ascii.eqlIgnoreCase(text, "true")) return .{ .boolean = true };
|
||||
if (std.ascii.eqlIgnoreCase(text, "false")) return .{ .boolean = false };
|
||||
if (std.fmt.parseInt(i64, text, 10)) |n| return .{ .int = n } else |_| {}
|
||||
if (std.fmt.parseFloat(f64, text)) |f| {
|
||||
if (std.math.isFinite(f)) return .{ .float = f };
|
||||
} else |_| {}
|
||||
return .{ .string = try arena.dupe(u8, text) };
|
||||
}
|
||||
|
||||
// -- platform paths --------------------------------------------------------------------
|
||||
|
||||
pub fn systemConfigDir(arena: Allocator, env: *const Environ.Map) Allocator.Error![]const u8 {
|
||||
if (builtin.os.tag == .windows) {
|
||||
const pd = env.get("PROGRAMDATA") orelse "C:\\ProgramData";
|
||||
return std.fmt.allocPrint(arena, "{s}\\zag", .{pd});
|
||||
}
|
||||
return "/etc/zag";
|
||||
}
|
||||
|
||||
pub fn userConfigDir(arena: Allocator, env: *const Environ.Map) Allocator.Error![]const u8 {
|
||||
const home = env.get("HOME") orelse env.get("USERPROFILE") orelse "";
|
||||
switch (builtin.os.tag) {
|
||||
.windows => {
|
||||
if (env.get("APPDATA")) |ad| return std.fmt.allocPrint(arena, "{s}\\zag", .{ad});
|
||||
return std.fmt.allocPrint(arena, "{s}\\AppData\\Roaming\\zag", .{home});
|
||||
},
|
||||
.macos => return std.fmt.allocPrint(arena, "{s}/Library/Application Support/zag", .{home}),
|
||||
else => return std.fmt.allocPrint(arena, "{s}/.config/zag", .{home}),
|
||||
}
|
||||
}
|
||||
|
||||
pub const conf_name = "zag.conf";
|
||||
|
||||
/// `[system zag.conf, user zag.conf]`, lowest precedence first.
|
||||
pub fn searchPaths(arena: Allocator, env: *const Environ.Map) Allocator.Error![]const []const u8 {
|
||||
const sep = if (builtin.os.tag == .windows) "\\" else "/";
|
||||
const paths = try arena.alloc([]const u8, 2);
|
||||
paths[0] = try std.fmt.allocPrint(arena, "{s}{s}{s}", .{ try systemConfigDir(arena, env), sep, conf_name });
|
||||
paths[1] = try std.fmt.allocPrint(arena, "{s}{s}{s}", .{ try userConfigDir(arena, env), sep, conf_name });
|
||||
return paths;
|
||||
}
|
||||
|
||||
// -- loading ---------------------------------------------------------------------------
|
||||
|
||||
/// Reads and parses one file. Returns null when it does not exist.
|
||||
pub fn loadFile(arena: Allocator, io: Io, path: []const u8, diag: ?*Diagnostic) Error!?toml.Doc {
|
||||
const text = Io.Dir.cwd().readFileAlloc(io, path, arena, .limited(1 << 20)) catch |err| switch (err) {
|
||||
error.FileNotFound => return null,
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
else => {
|
||||
if (diag) |d| d.path = path;
|
||||
return error.ReadFailed;
|
||||
},
|
||||
};
|
||||
var td: toml.Diagnostic = .{};
|
||||
return toml.parse(arena, text, &td) catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
else => {
|
||||
if (diag) |d| {
|
||||
d.path = path;
|
||||
d.line = td.line;
|
||||
}
|
||||
return error.ParseFailed;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
pub const LoadOptions = struct {
|
||||
/// Overrides the system/user search (used by tests).
|
||||
search_paths: ?[]const []const u8 = null,
|
||||
/// `--config <file>`; a bad explicit file is an error, a missing one is ignored.
|
||||
explicit_path: ?[]const u8 = null,
|
||||
};
|
||||
|
||||
/// 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 {
|
||||
var merged: toml.Doc = .empty;
|
||||
const paths = opts.search_paths orelse try searchPaths(arena, env);
|
||||
for (paths) |p| {
|
||||
const doc = loadFile(arena, io, p, null) catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
else => continue,
|
||||
};
|
||||
if (doc) |d| try mergeInto(arena, &merged, d);
|
||||
}
|
||||
if (opts.explicit_path) |p| {
|
||||
if (try loadFile(arena, io, p, diag)) |d| try mergeInto(arena, &merged, d);
|
||||
}
|
||||
try applyEnvironment(arena, &merged, env);
|
||||
return fromDoc(arena, merged, diag);
|
||||
}
|
||||
|
||||
// -- tests -----------------------------------------------------------------------------
|
||||
|
||||
fn testDoc(arena: Allocator, text: []const u8) !toml.Doc {
|
||||
return toml.parse(arena, text, null);
|
||||
}
|
||||
|
||||
test "defaults match barn" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const cfg = try fromDoc(arena.allocator(), .empty, null);
|
||||
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);
|
||||
try std.testing.expect(cfg.cleanup.enabled and cfg.cleanup.keep_failed_jobs);
|
||||
try std.testing.expectEqual(@as(u32, 72), cfg.cleanup.max_age_hours);
|
||||
try std.testing.expectEqual(@as(u32, 168), cfg.cleanup.keep_failed_jobs_hours);
|
||||
try std.testing.expectEqual(@as(u32, 50), cfg.storage.max_disk_usage_gb);
|
||||
try std.testing.expectEqualStrings("/tmp/zag/zag.sock", try cfg.ipcSocketPath(arena.allocator()));
|
||||
}
|
||||
|
||||
test "embedded default zag.conf parses to the built-in defaults" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
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);
|
||||
}
|
||||
|
||||
test "values, arrays and enums convert" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(),
|
||||
\\[service]
|
||||
\\log_level = "DEBUG"
|
||||
\\ipc_socket = "/run/zag.sock"
|
||||
\\[jobs]
|
||||
\\retry_on_exit_codes = [1, 137]
|
||||
\\retry_backoff_multiplier = 3
|
||||
\\[storage]
|
||||
\\base_dir = "/var/lib/zag"
|
||||
\\preserve_work_dir = true
|
||||
), null);
|
||||
try std.testing.expectEqual(LogLevel.debug, cfg.service.log_level);
|
||||
try std.testing.expectEqualStrings("/run/zag.sock", try cfg.ipcSocketPath(arena.allocator()));
|
||||
try std.testing.expectEqualSlices(i32, &.{ 1, 137 }, cfg.jobs.retry_on_exit_codes);
|
||||
try std.testing.expectEqual(@as(f64, 3.0), cfg.jobs.retry_backoff_multiplier);
|
||||
try std.testing.expect(cfg.storage.preserve_work_dir);
|
||||
}
|
||||
|
||||
test "ipc socket follows a custom base_dir" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const cfg = try fromDoc(arena.allocator(), try testDoc(arena.allocator(), "[storage]\nbase_dir = \"/data/zag\"\n"), null);
|
||||
try std.testing.expectEqualStrings("/data/zag/zag.sock", try cfg.ipcSocketPath(arena.allocator()));
|
||||
}
|
||||
|
||||
test "validation rejects bad values and names the key" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
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));
|
||||
try std.testing.expectEqualStrings("log_level", diag.key);
|
||||
try std.testing.expectError(error.OutOfRange, fromDoc(a, try testDoc(a, "[jobs]\nmax_retries = -1\n"), &diag));
|
||||
try std.testing.expectError(error.InvalidValue, fromDoc(a, try testDoc(a, "[cleanup]\nenabled = 5\n"), &diag));
|
||||
}
|
||||
|
||||
test "environment overrides, including load_levels" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
var env = Environ.Map.init(std.testing.allocator);
|
||||
defer env.deinit();
|
||||
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_CLEANUP_ENABLED", "false");
|
||||
try env.put("ZAG_SERVICE_LOG_LEVEL", "warn");
|
||||
try env.put("ZAG_JOBS_RETRY_BACKOFF_MULTIPLIER", "1.5");
|
||||
try env.put("ZAG_BASE_DIR", "ignored");
|
||||
try env.put("OTHER_JOBS_MAX_RETRIES", "99");
|
||||
|
||||
var doc = try testDoc(a, "[jobs]\nmax_retries = 2\n");
|
||||
try applyEnvironment(a, &doc, &env);
|
||||
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);
|
||||
}
|
||||
|
||||
test "files merge per key with explicit file and env on top" {
|
||||
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 = "system.conf", .data = "[jobs]\nmax_retries = 1\nretry_delay_seconds = 10\n[cleanup]\nmax_age_hours = 10\n" });
|
||||
try tmp.dir.writeFile(io, .{ .sub_path = "user.conf", .data = "[jobs]\nmax_retries = 2\n" });
|
||||
try tmp.dir.writeFile(io, .{ .sub_path = "explicit.conf", .data = "[cleanup]\nmax_age_hours = 20\n" });
|
||||
try tmp.dir.writeFile(io, .{ .sub_path = "broken.conf", .data = "[jobs\n" });
|
||||
|
||||
const base = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{tmp.sub_path});
|
||||
const paths = [_][]const u8{
|
||||
try std.fmt.allocPrint(a, "{s}/system.conf", .{base}),
|
||||
try std.fmt.allocPrint(a, "{s}/missing.conf", .{base}),
|
||||
try std.fmt.allocPrint(a, "{s}/broken.conf", .{base}), // skipped, not fatal
|
||||
try std.fmt.allocPrint(a, "{s}/user.conf", .{base}),
|
||||
};
|
||||
var env = Environ.Map.init(std.testing.allocator);
|
||||
defer env.deinit();
|
||||
try env.put("ZAG_JOBS_RETRY_DELAY_SECONDS", "99");
|
||||
|
||||
const cfg = try load(a, io, &env, .{
|
||||
.search_paths = &paths,
|
||||
.explicit_path = try std.fmt.allocPrint(a, "{s}/explicit.conf", .{base}),
|
||||
}, 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
|
||||
|
||||
var diag: Diagnostic = .{};
|
||||
try std.testing.expectError(error.ParseFailed, load(a, io, &env, .{
|
||||
.search_paths = &.{},
|
||||
.explicit_path = try std.fmt.allocPrint(a, "{s}/broken.conf", .{base}),
|
||||
}, &diag));
|
||||
try std.testing.expectEqual(@as(usize, 1), diag.line);
|
||||
}
|
||||
|
||||
test "search paths point at zag.conf" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
var env = Environ.Map.init(std.testing.allocator);
|
||||
defer env.deinit();
|
||||
try env.put("HOME", "/home/dan");
|
||||
const paths = try searchPaths(arena.allocator(), &env);
|
||||
try std.testing.expectEqualStrings("/etc/zag/zag.conf", paths[0]);
|
||||
try std.testing.expectEqualStrings("/home/dan/.config/zag/zag.conf", paths[1]);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
//! 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 },
|
||||
};
|
||||
@@ -0,0 +1,16 @@
|
||||
# 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
|
||||
@@ -0,0 +1,16 @@
|
||||
# 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
|
||||
@@ -0,0 +1,4 @@
|
||||
# Medium load commands
|
||||
# Maximum concurrent: 8 (default)
|
||||
#
|
||||
# Empty by default - unmatched commands are classified as MEDIUM
|
||||
@@ -0,0 +1,67 @@
|
||||
# Zag Configuration
|
||||
# Generated by: zag config install
|
||||
|
||||
[service]
|
||||
# Logging verbosity: debug, info, warn, error
|
||||
log_level = "info"
|
||||
|
||||
# DEPRECATED: Use [load_levels] section instead
|
||||
# max_concurrent_jobs = 4
|
||||
|
||||
# How often running jobs update their heartbeat (seconds)
|
||||
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
|
||||
|
||||
# Number of retry attempts for failed jobs
|
||||
max_retries = 3
|
||||
|
||||
# Initial delay before first retry (seconds)
|
||||
retry_delay_seconds = 30
|
||||
|
||||
# Multiplier applied to delay after each retry
|
||||
retry_backoff_multiplier = 2.0
|
||||
|
||||
# Only retry on these exit codes (empty = retry all failures)
|
||||
retry_on_exit_codes = []
|
||||
|
||||
[cleanup]
|
||||
# Enable automatic cleanup of old jobs
|
||||
enabled = true
|
||||
|
||||
# Remove jobs older than this (hours)
|
||||
max_age_hours = 72
|
||||
|
||||
# How often the cleanup task runs (minutes)
|
||||
cleanup_interval_minutes = 60
|
||||
|
||||
# Preserve failed jobs for debugging
|
||||
keep_failed_jobs = true
|
||||
|
||||
# How long to keep failed jobs (hours)
|
||||
keep_failed_jobs_hours = 168
|
||||
|
||||
[storage]
|
||||
# Root directory for all Zag data
|
||||
base_dir = "/tmp/zag"
|
||||
|
||||
# Maximum disk space Zag can use (GB)
|
||||
max_disk_usage_gb = 50
|
||||
|
||||
# Keep work/input and work/output after job completion
|
||||
preserve_work_dir = false
|
||||
@@ -0,0 +1,189 @@
|
||||
//! 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"),
|
||||
};
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
@@ -11,6 +11,9 @@ 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");
|
||||
|
||||
test {
|
||||
@import("std").testing.refAllDecls(@This());
|
||||
|
||||
Reference in new issue
Block a user