feat: per-job timeout, shared job query, config problem report, atomic job deletion; arg parser (M5 part 2)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bd4e585ed8
commit
35106d405b
9 files changed
+511
-28
No files matched your search
+235
@@ -0,0 +1,235 @@
|
||||
//! Command-line option parsing: `--long`, `--long=value`, `--long value`, `-s`, `-svalue`,
|
||||
//! `-s value`, grouped short flags (`-fq`), and `--` to end option parsing.
|
||||
//! With `stop_at_positional`, the first non-option token ends parsing so the rest can be
|
||||
//! passed through verbatim (`zag run curl -u user -o file url`).
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
|
||||
pub const Opt = struct {
|
||||
long: []const u8,
|
||||
short: ?u8 = null,
|
||||
takes_value: bool = false,
|
||||
};
|
||||
|
||||
pub const Error = error{ UnknownOption, MissingValue, UnexpectedValue } || Allocator.Error;
|
||||
|
||||
pub const Diagnostic = struct {
|
||||
/// The offending token (or option name), borrowed from the arguments.
|
||||
token: []const u8 = "",
|
||||
};
|
||||
|
||||
pub const Options = struct {
|
||||
stop_at_positional: bool = false,
|
||||
};
|
||||
|
||||
pub const Parsed = struct {
|
||||
flags: []const []const u8 = &.{},
|
||||
values: []const Pair = &.{},
|
||||
positionals: []const []const u8 = &.{},
|
||||
|
||||
pub const Pair = struct { name: []const u8, value: []const u8 };
|
||||
|
||||
pub fn flag(self: Parsed, name: []const u8) bool {
|
||||
for (self.flags) |f| if (std.mem.eql(u8, f, name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// The last value given for `name`.
|
||||
pub fn value(self: Parsed, name: []const u8) ?[]const u8 {
|
||||
var i = self.values.len;
|
||||
while (i > 0) {
|
||||
i -= 1;
|
||||
if (std.mem.eql(u8, self.values[i].name, name)) return self.values[i].value;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// Adds everything from `other` (later values win in `value`).
|
||||
pub fn merge(self: Parsed, arena: Allocator, other: Parsed) Allocator.Error!Parsed {
|
||||
return .{
|
||||
.flags = try std.mem.concat(arena, []const u8, &.{ self.flags, other.flags }),
|
||||
.values = try std.mem.concat(arena, Pair, &.{ self.values, other.values }),
|
||||
.positionals = try std.mem.concat(arena, []const u8, &.{ self.positionals, other.positionals }),
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
fn findLong(specs: []const Opt, name: []const u8) ?Opt {
|
||||
for (specs) |s| if (std.mem.eql(u8, s.long, name)) return s;
|
||||
return null;
|
||||
}
|
||||
|
||||
fn findShort(specs: []const Opt, c: u8) ?Opt {
|
||||
for (specs) |s| if (s.short) |sc| if (sc == c) return s;
|
||||
return null;
|
||||
}
|
||||
|
||||
pub fn parse(arena: Allocator, args: []const []const u8, specs: []const Opt, opts: Options, diag: ?*Diagnostic) Error!Parsed {
|
||||
var flags: std.ArrayList([]const u8) = .empty;
|
||||
var values: std.ArrayList(Parsed.Pair) = .empty;
|
||||
var positionals: std.ArrayList([]const u8) = .empty;
|
||||
|
||||
var i: usize = 0;
|
||||
while (i < args.len) : (i += 1) {
|
||||
const arg = args[i];
|
||||
if (std.mem.eql(u8, arg, "--")) {
|
||||
try positionals.appendSlice(arena, args[i + 1 ..]);
|
||||
break;
|
||||
}
|
||||
const is_long = std.mem.startsWith(u8, arg, "--");
|
||||
const is_short = !is_long and arg.len > 1 and arg[0] == '-';
|
||||
if (!is_long and !is_short) {
|
||||
if (opts.stop_at_positional) {
|
||||
try positionals.appendSlice(arena, args[i..]);
|
||||
break;
|
||||
}
|
||||
try positionals.append(arena, arg);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (is_long) {
|
||||
const body = arg[2..];
|
||||
const eq = std.mem.indexOfScalar(u8, body, '=');
|
||||
const name = if (eq) |e| body[0..e] else body;
|
||||
const spec = findLong(specs, name) orelse return fail(diag, arg, error.UnknownOption);
|
||||
if (spec.takes_value) {
|
||||
if (eq) |e| {
|
||||
try values.append(arena, .{ .name = spec.long, .value = body[e + 1 ..] });
|
||||
} else {
|
||||
i += 1;
|
||||
if (i >= args.len) return fail(diag, arg, error.MissingValue);
|
||||
try values.append(arena, .{ .name = spec.long, .value = args[i] });
|
||||
}
|
||||
} else {
|
||||
if (eq != null) return fail(diag, arg, error.UnexpectedValue);
|
||||
try flags.append(arena, spec.long);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// Short options: -f, -fq, -n5, -n 5
|
||||
var j: usize = 1;
|
||||
while (j < arg.len) : (j += 1) {
|
||||
const spec = findShort(specs, arg[j]) orelse return fail(diag, arg, error.UnknownOption);
|
||||
if (!spec.takes_value) {
|
||||
try flags.append(arena, spec.long);
|
||||
continue;
|
||||
}
|
||||
if (j + 1 < arg.len) {
|
||||
const rest = arg[j + 1 ..];
|
||||
try values.append(arena, .{ .name = spec.long, .value = if (rest[0] == '=') rest[1..] else rest });
|
||||
} else {
|
||||
i += 1;
|
||||
if (i >= args.len) return fail(diag, arg, error.MissingValue);
|
||||
try values.append(arena, .{ .name = spec.long, .value = args[i] });
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
return .{
|
||||
.flags = try flags.toOwnedSlice(arena),
|
||||
.values = try values.toOwnedSlice(arena),
|
||||
.positionals = try positionals.toOwnedSlice(arena),
|
||||
};
|
||||
}
|
||||
|
||||
fn fail(diag: ?*Diagnostic, token: []const u8, err: Error) Error {
|
||||
if (diag) |d| d.token = token;
|
||||
return err;
|
||||
}
|
||||
|
||||
// -- tests -----------------------------------------------------------------------------
|
||||
|
||||
const test_specs = [_]Opt{
|
||||
.{ .long = "output", .short = 'o', .takes_value = true },
|
||||
.{ .long = "tag", .short = 't', .takes_value = true },
|
||||
.{ .long = "force", .short = 'f' },
|
||||
.{ .long = "quiet", .short = 'q' },
|
||||
.{ .long = "offline" },
|
||||
.{ .long = "limit", .short = 'n', .takes_value = true },
|
||||
};
|
||||
|
||||
fn parseT(arena: Allocator, args: []const []const u8, opts: Options) !Parsed {
|
||||
return parse(arena, args, &test_specs, opts, null);
|
||||
}
|
||||
|
||||
test "long options with = and separate values, flags, positionals" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const p = try parseT(arena.allocator(), &.{ "--output=json", "job-1", "--tag", "x", "--offline", "job-2" }, .{});
|
||||
try std.testing.expectEqualStrings("json", p.value("output").?);
|
||||
try std.testing.expectEqualStrings("x", p.value("tag").?);
|
||||
try std.testing.expect(p.flag("offline"));
|
||||
try std.testing.expect(!p.flag("force"));
|
||||
try std.testing.expectEqual(@as(usize, 2), p.positionals.len);
|
||||
try std.testing.expectEqualStrings("job-2", p.positionals[1]);
|
||||
}
|
||||
|
||||
test "short options: values, attached values, grouped flags" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const p = try parseT(arena.allocator(), &.{ "-o", "xml", "-n5", "-fq", "-t=demo" }, .{});
|
||||
try std.testing.expectEqualStrings("xml", p.value("output").?);
|
||||
try std.testing.expectEqualStrings("5", p.value("limit").?);
|
||||
try std.testing.expect(p.flag("force") and p.flag("quiet"));
|
||||
try std.testing.expectEqualStrings("demo", p.value("tag").?);
|
||||
}
|
||||
|
||||
test "later values win" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const p = try parseT(arena.allocator(), &.{ "-o", "json", "--output", "xml" }, .{});
|
||||
try std.testing.expectEqualStrings("xml", p.value("output").?);
|
||||
}
|
||||
|
||||
test "-- ends option parsing" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const p = try parseT(arena.allocator(), &.{ "--tag", "t", "--", "ffmpeg", "-i", "in.mp4", "--force" }, .{});
|
||||
try std.testing.expectEqualStrings("t", p.value("tag").?);
|
||||
try std.testing.expect(!p.flag("force"));
|
||||
try std.testing.expectEqual(@as(usize, 4), p.positionals.len);
|
||||
try std.testing.expectEqualStrings("--force", p.positionals[3]);
|
||||
}
|
||||
|
||||
test "stop_at_positional passes the rest through verbatim" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const p = try parseT(arena.allocator(), &.{ "--output=json", "curl", "-u", "user:pw", "-o", "/tmp/f", "url" }, .{ .stop_at_positional = true });
|
||||
try std.testing.expectEqualStrings("json", p.value("output").?);
|
||||
try std.testing.expect(p.value("output") != null and p.value("tag") == null);
|
||||
try std.testing.expectEqual(@as(usize, 6), p.positionals.len);
|
||||
try std.testing.expectEqualStrings("curl", p.positionals[0]);
|
||||
try std.testing.expectEqualStrings("-o", p.positionals[3]);
|
||||
}
|
||||
|
||||
test "a lone dash is a positional" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const p = try parseT(arena.allocator(), &.{"-"}, .{});
|
||||
try std.testing.expectEqual(@as(usize, 1), p.positionals.len);
|
||||
}
|
||||
|
||||
test "errors name the token" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
var d: Diagnostic = .{};
|
||||
try std.testing.expectError(error.UnknownOption, parse(arena.allocator(), &.{"--bogus"}, &test_specs, .{}, &d));
|
||||
try std.testing.expectEqualStrings("--bogus", d.token);
|
||||
try std.testing.expectError(error.UnknownOption, parse(arena.allocator(), &.{"-z"}, &test_specs, .{}, &d));
|
||||
try std.testing.expectError(error.MissingValue, parse(arena.allocator(), &.{"--output"}, &test_specs, .{}, &d));
|
||||
try std.testing.expectEqualStrings("--output", d.token);
|
||||
try std.testing.expectError(error.MissingValue, parse(arena.allocator(), &.{"-n"}, &test_specs, .{}, &d));
|
||||
try std.testing.expectError(error.UnexpectedValue, parse(arena.allocator(), &.{"--force=1"}, &test_specs, .{}, &d));
|
||||
}
|
||||
|
||||
test "merge combines two parses" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = try parseT(arena.allocator(), &.{ "-o", "json", "--offline" }, .{});
|
||||
const b = try parseT(arena.allocator(), &.{ "-o", "xml", "pos" }, .{});
|
||||
const m = try a.merge(arena.allocator(), b);
|
||||
try std.testing.expectEqualStrings("xml", m.value("output").?);
|
||||
try std.testing.expect(m.flag("offline"));
|
||||
try std.testing.expectEqual(@as(usize, 1), m.positionals.len);
|
||||
}
|
||||
+122
@@ -184,6 +184,94 @@ pub fn fromDoc(arena: Allocator, doc: toml.Doc, diag: ?*Diagnostic) Error!Config
|
||||
return cfg;
|
||||
}
|
||||
|
||||
// -- validation report -----------------------------------------------------------------
|
||||
|
||||
pub const Problem = struct {
|
||||
section: []const u8,
|
||||
/// Empty for problems that concern a whole section.
|
||||
key: []const u8,
|
||||
message: []const u8,
|
||||
};
|
||||
|
||||
const known_sections = [_][]const u8{ "service", "jobs", "cleanup", "storage", "load_levels" };
|
||||
|
||||
fn expectation(comptime T: type) []const u8 {
|
||||
return switch (@typeInfo(T)) {
|
||||
.optional => |o| expectation(o.child),
|
||||
.bool => "true or false",
|
||||
.int => "a non-negative integer",
|
||||
.float => "a number",
|
||||
.@"enum" => blk: {
|
||||
comptime var names: []const u8 = "one of ";
|
||||
inline for (@typeInfo(T).@"enum".fields, 0..) |f, i| names = names ++ (if (i > 0) ", " else "") ++ f.name;
|
||||
break :blk names;
|
||||
},
|
||||
.pointer => |p| if (p.child == u8) "a string" else "a list of integers",
|
||||
else => "a valid value",
|
||||
};
|
||||
}
|
||||
|
||||
fn checkSection(arena: Allocator, comptime T: type, name: []const u8, section: toml.Section, out: *std.ArrayList(Problem)) Allocator.Error!void {
|
||||
var it = section.iterator();
|
||||
while (it.next()) |entry| {
|
||||
const key = entry.key_ptr.*;
|
||||
var known = false;
|
||||
inline for (@typeInfo(T).@"struct".fields) |f| {
|
||||
if (std.mem.eql(u8, key, f.name)) {
|
||||
known = true;
|
||||
if (convert(arena, f.type, entry.value_ptr.*)) |_| {} else |err| {
|
||||
const msg = switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
else => try std.fmt.allocPrint(arena, "Invalid value for '{s}': must be {s}", .{ key, expectation(f.type) }),
|
||||
};
|
||||
try out.append(arena, .{ .section = name, .key = key, .message = msg });
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!known) {
|
||||
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.
|
||||
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 {
|
||||
try out.append(arena, .{
|
||||
.section = name,
|
||||
.key = "",
|
||||
.message = try std.fmt.allocPrint(arena, "Unknown section: [{s}]", .{name}),
|
||||
});
|
||||
}
|
||||
}
|
||||
if (out.items.len == 0) {
|
||||
// Types are fine; now check ranges on the resulting configuration.
|
||||
var diag: Diagnostic = .{};
|
||||
_ = fromDoc(arena, doc, &diag) catch |err| switch (err) {
|
||||
error.OutOfMemory => return error.OutOfMemory,
|
||||
else => try out.append(arena, .{
|
||||
.section = diag.section,
|
||||
.key = diag.key,
|
||||
.message = try std.fmt.allocPrint(arena, "Invalid value for '{s}': {s}", .{
|
||||
diag.key,
|
||||
if (std.mem.eql(u8, diag.key, "retry_backoff_multiplier")) "must be at least 1.0" else "must be a positive integer",
|
||||
}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
return out.toOwnedSlice(arena);
|
||||
}
|
||||
|
||||
// -- merging ---------------------------------------------------------------------------
|
||||
|
||||
/// Copies every key of `src` into `dst`, overriding existing keys.
|
||||
@@ -477,3 +565,37 @@ test "search paths point at zag.conf" {
|
||||
try std.testing.expectEqualStrings("/etc/zag/zag.conf", paths[0]);
|
||||
try std.testing.expectEqualStrings("/home/dan/.config/zag/zag.conf", paths[1]);
|
||||
}
|
||||
|
||||
test "problems reports unknown names, bad types and ranges" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const a = arena.allocator();
|
||||
|
||||
try std.testing.expectEqual(@as(usize, 0), (try problems(a, try testDoc(a, "[jobs]\nmax_retries = 2\n"))).len);
|
||||
|
||||
const ps = try problems(a, try testDoc(a,
|
||||
\\[bogus]
|
||||
\\x = 1
|
||||
\\[service]
|
||||
\\log_level = "loud"
|
||||
\\nope = 1
|
||||
\\[cleanup]
|
||||
\\enabled = 5
|
||||
));
|
||||
try std.testing.expectEqual(@as(usize, 4), ps.len);
|
||||
var saw_section = false;
|
||||
var saw_key = false;
|
||||
var saw_level = false;
|
||||
var saw_bool = false;
|
||||
for (ps) |p| {
|
||||
if (std.mem.eql(u8, p.message, "Unknown section: [bogus]")) saw_section = true;
|
||||
if (std.mem.eql(u8, p.message, "Unknown key 'nope' in [service] section")) saw_key = true;
|
||||
if (std.mem.indexOf(u8, p.message, "must be one of debug, info, warn, error") != null) saw_level = true;
|
||||
if (std.mem.indexOf(u8, p.message, "'enabled': must be true or false") != null) saw_bool = true;
|
||||
}
|
||||
try std.testing.expect(saw_section and saw_key and saw_level and saw_bool);
|
||||
|
||||
const range = try problems(a, try testDoc(a, "[jobs]\nretry_backoff_multiplier = 0.5\n"));
|
||||
try std.testing.expectEqual(@as(usize, 1), range.len);
|
||||
try std.testing.expectEqualStrings("retry_backoff_multiplier", range[0].key);
|
||||
}
|
||||
+45
-2
@@ -9,6 +9,9 @@ const Io = std.Io;
|
||||
const Dir = Io.Dir;
|
||||
|
||||
pub const jobs_dir = "jobs";
|
||||
/// Job directories are renamed to `jobs/.trash-<id>` before deletion so a half-deleted job is
|
||||
/// never visible as a job.
|
||||
pub const trash_prefix = ".trash-";
|
||||
pub const locks_dir = "locks";
|
||||
pub const logs_dir = "logs";
|
||||
pub const work_dir = "work";
|
||||
@@ -45,6 +48,17 @@ pub const Dirs = struct {
|
||||
try self.base.createDirPath(io, jobs_dir);
|
||||
try self.base.createDirPath(io, locks_dir);
|
||||
try self.base.createDirPath(io, logs_dir);
|
||||
self.sweepTrash(io);
|
||||
}
|
||||
|
||||
/// Removes half-deleted job directories left behind by a crash.
|
||||
fn sweepTrash(self: *Dirs, io: Io) void {
|
||||
var jobs = self.base.openDir(io, jobs_dir, .{ .iterate = true }) catch return;
|
||||
defer jobs.close(io);
|
||||
var it = jobs.iterate();
|
||||
while (it.next(io) catch null) |entry| {
|
||||
if (std.mem.startsWith(u8, entry.name, trash_prefix)) jobs.deleteTree(io, entry.name) catch {};
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates `jobs/<id>/{work/input,work/output,logs}`.
|
||||
@@ -67,9 +81,18 @@ pub const Dirs = struct {
|
||||
return self.base.openDir(io, try std.fmt.bufPrint(&buf, "{s}/{s}", .{ jobs_dir, id }), .{});
|
||||
}
|
||||
|
||||
/// Atomically hides the job (rename into the trash namespace), then removes it.
|
||||
pub fn deleteJob(self: *Dirs, io: Io, id: []const u8) !void {
|
||||
var buf: [256]u8 = undefined;
|
||||
try self.base.deleteTree(io, try std.fmt.bufPrint(&buf, "{s}/{s}", .{ jobs_dir, id }));
|
||||
var from: [256]u8 = undefined;
|
||||
var to: [256]u8 = undefined;
|
||||
const src = try std.fmt.bufPrint(&from, "{s}/{s}", .{ jobs_dir, id });
|
||||
const dst = try std.fmt.bufPrint(&to, "{s}/{s}{s}", .{ jobs_dir, trash_prefix, id });
|
||||
self.base.deleteTree(io, dst) catch {}; // leftover from an earlier crash
|
||||
self.base.rename(src, self.base, dst, io) catch |err| switch (err) {
|
||||
error.FileNotFound => return,
|
||||
else => |e| return e,
|
||||
};
|
||||
try self.base.deleteTree(io, dst);
|
||||
}
|
||||
|
||||
/// Absolute-or-relative path strings for display, allocated from `arena`.
|
||||
@@ -98,3 +121,23 @@ test "open creates the skeleton and job dirs" {
|
||||
try d.deleteJob(io, "job-aaaaaaaa");
|
||||
try std.testing.expect(!d.jobExists(io, "job-aaaaaaaa"));
|
||||
}
|
||||
|
||||
test "deleteJob leaves no trash and initialize sweeps stale trash" {
|
||||
const io = std.testing.io;
|
||||
var tmp = std.testing.tmpDir(.{});
|
||||
defer tmp.cleanup();
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const base = try std.fmt.allocPrint(arena.allocator(), ".zig-cache/tmp/{s}/zag", .{tmp.sub_path});
|
||||
var d = try Dirs.open(io, base);
|
||||
defer d.close(io);
|
||||
|
||||
try d.createJobDirs(io, "job-bbbbbbbb");
|
||||
try d.deleteJob(io, "job-bbbbbbbb");
|
||||
try std.testing.expectError(error.FileNotFound, d.base.statFile(io, "jobs/.trash-job-bbbbbbbb", .{}));
|
||||
try d.deleteJob(io, "job-bbbbbbbb"); // already gone: not an error
|
||||
|
||||
try d.base.createDirPath(io, "jobs/.trash-job-cccccccc/work");
|
||||
try d.initialize(io);
|
||||
try std.testing.expectError(error.FileNotFound, d.base.statFile(io, "jobs/.trash-job-cccccccc", .{}));
|
||||
}
|
||||
@@ -55,6 +55,8 @@ pub const Manifest = struct {
|
||||
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,
|
||||
|
||||
pub const ValidationError = error{ BlankId, EmptyCommand, BadBackoff };
|
||||
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
//! Job listing queries shared by the daemon (`get_status`) and the CLI's offline mode.
|
||||
const std = @import("std");
|
||||
const Allocator = std.mem.Allocator;
|
||||
const Repository = @import("repository.zig").Repository;
|
||||
const Job = @import("job.zig").Job;
|
||||
const State = @import("state.zig").State;
|
||||
|
||||
pub const Filter = struct {
|
||||
tag: ?[]const u8 = null,
|
||||
state: ?State = null,
|
||||
/// Keep only the newest `limit` jobs when positive.
|
||||
limit: ?usize = null,
|
||||
};
|
||||
|
||||
fn newerFirst(_: void, a: Job, b: Job) bool {
|
||||
return a.created_at > b.created_at;
|
||||
}
|
||||
|
||||
/// Jobs matching `filter`, newest first. Memory comes from `arena`.
|
||||
pub fn selectJobs(arena: Allocator, repo: Repository, filter: Filter) ![]Job {
|
||||
var list: std.ArrayList(Job) = .empty;
|
||||
for (try repo.findAll(arena)) |j| {
|
||||
if (filter.tag) |t| if (j.tag == null or !std.mem.eql(u8, t, j.tag.?)) continue;
|
||||
if (filter.state) |s| if (j.state != s) continue;
|
||||
try list.append(arena, j);
|
||||
}
|
||||
std.mem.sort(Job, list.items, {}, newerFirst);
|
||||
if (filter.limit) |n| if (n > 0 and list.items.len > n) list.shrinkRetainingCapacity(n);
|
||||
return list.items;
|
||||
}
|
||||
|
||||
test "selectJobs filters, sorts newest first and limits" {
|
||||
const Dirs = @import("dirs.zig").Dirs;
|
||||
const io = std.testing.io;
|
||||
var tmp = std.testing.tmpDir(.{});
|
||||
defer tmp.cleanup();
|
||||
var arena_state = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena_state.deinit();
|
||||
const a = arena_state.allocator();
|
||||
const base = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}/zag", .{tmp.sub_path});
|
||||
var dirs = try Dirs.open(io, base);
|
||||
defer dirs.close(io);
|
||||
const repo = Repository.init(io, &dirs);
|
||||
|
||||
const j1 = try repo.create(a, &.{"a"}, .{ .tag = "x" });
|
||||
try io.sleep(.fromMilliseconds(5), .real);
|
||||
const j2 = try repo.create(a, &.{"b"}, .{ .tag = "y" });
|
||||
try io.sleep(.fromMilliseconds(5), .real);
|
||||
const j3 = try repo.create(a, &.{"c"}, .{ .tag = "x" });
|
||||
try repo.markStarted(j3.id, 1);
|
||||
|
||||
const all = try selectJobs(a, repo, .{});
|
||||
try std.testing.expectEqualStrings(j3.id, all[0].id);
|
||||
try std.testing.expectEqualStrings(j1.id, all[2].id);
|
||||
try std.testing.expectEqual(@as(usize, 2), (try selectJobs(a, repo, .{ .tag = "x" })).len);
|
||||
try std.testing.expectEqual(@as(usize, 1), (try selectJobs(a, repo, .{ .state = .running })).len);
|
||||
const limited = try selectJobs(a, repo, .{ .limit = 1 });
|
||||
try std.testing.expectEqual(@as(usize, 1), limited.len);
|
||||
try std.testing.expectEqualStrings(j3.id, limited[0].id);
|
||||
_ = j2;
|
||||
}
|
||||
+22
-5
@@ -30,6 +30,7 @@ pub const CreateOptions = struct {
|
||||
max_retries: u32 = 3,
|
||||
retry_delay_seconds: u32 = 30,
|
||||
retry_backoff_multiplier: f64 = 2.0,
|
||||
timeout_seconds: ?u32 = null,
|
||||
};
|
||||
|
||||
pub const Repository = struct {
|
||||
@@ -66,6 +67,7 @@ pub const Repository = struct {
|
||||
.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();
|
||||
|
||||
@@ -73,16 +75,18 @@ pub const Repository = struct {
|
||||
var job_dir = try self.dirs.openJob(self.io, id_str);
|
||||
defer job_dir.close(self.io);
|
||||
|
||||
var aw: Io.Writer.Allocating = .init(arena);
|
||||
try writeManifestJson(&aw.writer, manifest);
|
||||
try fsutil.writeAtomic(self.io, job_dir, manifest_file, aw.written());
|
||||
|
||||
// State files first, manifest last: a job only becomes visible (`findAll` requires the
|
||||
// manifest) once everything else is in place, so the scheduler never sees a half-made job.
|
||||
const sf = StateFiles.init(self.io, job_dir);
|
||||
try sf.writeState(.queued);
|
||||
try sf.writeCreatedAt(manifest.created_at);
|
||||
if (opts.tag) |t| try sf.writeTag(t);
|
||||
try sf.writeRetryCount(0);
|
||||
|
||||
var aw: Io.Writer.Allocating = .init(arena);
|
||||
try writeManifestJson(&aw.writer, manifest);
|
||||
try fsutil.writeAtomic(self.io, job_dir, manifest_file, aw.written());
|
||||
|
||||
return .{
|
||||
.id = id_str,
|
||||
.state = .queued,
|
||||
@@ -111,7 +115,7 @@ pub const Repository = struct {
|
||||
var list: std.ArrayList(Job) = .empty;
|
||||
var it = jobs_dir.iterate();
|
||||
while (try it.next(self.io)) |entry| {
|
||||
if (entry.kind != .directory) continue;
|
||||
if (entry.kind != .directory or !jobid.isValid(entry.name)) continue;
|
||||
const j = self.loadJob(arena, entry.name) catch continue;
|
||||
try list.append(arena, j);
|
||||
}
|
||||
@@ -295,6 +299,7 @@ pub fn writeManifestJson(out: *Io.Writer, m: Manifest) !void {
|
||||
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();
|
||||
}
|
||||
|
||||
@@ -307,6 +312,7 @@ const RawManifest = struct {
|
||||
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.
|
||||
@@ -322,6 +328,7 @@ pub fn parseManifestJson(arena: Allocator, text: []const u8) !Manifest {
|
||||
.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;
|
||||
return m;
|
||||
@@ -515,3 +522,13 @@ test "findAll, findByState and delete" {
|
||||
try std.testing.expectEqual(@as(usize, 1), (try r.findAll(a)).len);
|
||||
try std.testing.expect((try r.findById(a, j1.id)) == null);
|
||||
}
|
||||
|
||||
test "per-job timeout round-trips through the manifest" {
|
||||
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
|
||||
defer arena.deinit();
|
||||
const m: Manifest = .{ .id = "job-1", .command = &.{"x"}, .created_at = 0, .timeout_seconds = 90 };
|
||||
var aw: Io.Writer.Allocating = .init(arena.allocator());
|
||||
try writeManifestJson(&aw.writer, m);
|
||||
try std.testing.expect(std.mem.indexOf(u8, aw.written(), "\"timeoutSeconds\" : 90") != null);
|
||||
try std.testing.expectEqual(@as(?u32, 90), (try parseManifestJson(arena.allocator(), aw.written())).timeout_seconds);
|
||||
}
|
||||
@@ -28,6 +28,8 @@ pub const ipc = @import("ipc.zig");
|
||||
pub const service = @import("service.zig");
|
||||
pub const daemon = @import("daemon.zig");
|
||||
pub const output = @import("output.zig");
|
||||
pub const args = @import("args.zig");
|
||||
pub const query = @import("query.zig");
|
||||
|
||||
test {
|
||||
@import("std").testing.refAllDecls(@This());
|
||||
|
||||
+13
-2
@@ -157,7 +157,9 @@ fn runInner(gpa: Allocator, io: Io, repo: Repository, id: []const u8, ctl: *Cont
|
||||
return err;
|
||||
};
|
||||
|
||||
var monitor: Monitor = .{ .io = io, .repo = repo, .id = id, .ctl = ctl, .opts = opts, .pid = pid, .job_dir = job_dir, .gpa = gpa };
|
||||
var job_opts = opts;
|
||||
if (manifest.timeout_seconds) |t| job_opts.timeout_seconds = t;
|
||||
var monitor: Monitor = .{ .io = io, .repo = repo, .id = id, .ctl = ctl, .opts = job_opts, .pid = pid, .job_dir = job_dir, .gpa = gpa };
|
||||
if (opts.usage_interval_ms > 0) monitor.sampleUsage();
|
||||
const thread = std.Thread.spawn(.{}, Monitor.loop, .{&monitor}) catch null;
|
||||
const term = child.wait(io);
|
||||
@@ -173,7 +175,7 @@ fn runInner(gpa: Allocator, io: Io, repo: Repository, id: []const u8, ctl: *Cont
|
||||
return .canceled;
|
||||
}
|
||||
if (monitor.timed_out.load(.acquire)) {
|
||||
const msg = try std.fmt.allocPrint(arena, "Job exceeded timeout of {d} seconds", .{opts.timeout_seconds});
|
||||
const msg = try std.fmt.allocPrint(arena, "Job exceeded timeout of {d} seconds", .{job_opts.timeout_seconds});
|
||||
repo.markFailed(id, "timeout", msg) catch {};
|
||||
return .timed_out;
|
||||
}
|
||||
@@ -391,3 +393,12 @@ test "usage samples are logged while a job runs" {
|
||||
try std.testing.expect(rows.len >= 3); // start + periodic + stop
|
||||
try std.testing.expect(rows[0].memory_bytes > 0);
|
||||
}
|
||||
|
||||
test "a per-job timeout overrides the default" {
|
||||
const env = try TestEnv.init();
|
||||
defer env.deinit();
|
||||
const id = try env.create(&.{ "sleep", "30" }, .{ .timeout_seconds = 1 });
|
||||
var ctl: Control = .{};
|
||||
// Options carry no timeout; the manifest's own value applies.
|
||||
try std.testing.expectEqual(Outcome.timed_out, run(std.testing.allocator, std.testing.io, env.repo(), id, &ctl, fast));
|
||||
}
|
||||
+9
-19
@@ -17,6 +17,7 @@ const recovery = @import("recovery.zig");
|
||||
const cleanup = @import("cleanup.zig");
|
||||
const ipc = @import("ipc.zig");
|
||||
const jobjson = @import("jobjson.zig");
|
||||
const query = @import("query.zig");
|
||||
const jsonpretty = @import("jsonpretty.zig");
|
||||
const duration = @import("duration.zig");
|
||||
const timestamp = @import("timestamp.zig");
|
||||
@@ -256,28 +257,14 @@ pub const Service = struct {
|
||||
try w.endObject();
|
||||
}
|
||||
|
||||
fn newerFirst(_: void, a: Job, b: Job) bool {
|
||||
return a.created_at > b.created_at;
|
||||
}
|
||||
|
||||
fn hGetStatus(self: *Service, req: ipc.Request, res: *ipc.Response) !void {
|
||||
const tag = req.payloadString("tag");
|
||||
var want: ?state_mod.State = null;
|
||||
if (req.payloadString("state")) |s| want = state_mod.State.parse(s) orelse
|
||||
var filter: query.Filter = .{ .tag = req.payloadString("tag") };
|
||||
if (req.payloadString("state")) |s| filter.state = state_mod.State.parse(s) orelse
|
||||
return res.failFmt(.INVALID_REQUEST, "Unknown state: {s}", .{s});
|
||||
|
||||
var list: std.ArrayList(Job) = .empty;
|
||||
for (try self.repo.findAll(res.arena)) |j| {
|
||||
if (tag) |t| if (j.tag == null or !std.mem.eql(u8, t, j.tag.?)) continue;
|
||||
if (want) |s| if (j.state != s) continue;
|
||||
try list.append(res.arena, j);
|
||||
}
|
||||
std.mem.sort(Job, list.items, {}, newerFirst);
|
||||
var out: []const Job = list.items;
|
||||
if (req.payloadInt("limit")) |n| if (n > 0 and out.len > n) {
|
||||
out = out[0..@intCast(n)];
|
||||
if (req.payloadInt("limit")) |n| if (n > 0) {
|
||||
filter.limit = @intCast(n);
|
||||
};
|
||||
try jobjson.writeJobs(&res.json, out);
|
||||
try jobjson.writeJobs(&res.json, try query.selectJobs(res.arena, self.repo, filter));
|
||||
}
|
||||
|
||||
fn hGetJob(self: *Service, req: ipc.Request, res: *ipc.Response) !void {
|
||||
@@ -320,6 +307,9 @@ pub const Service = struct {
|
||||
if (req.payloadInt("retryDelaySeconds")) |n| {
|
||||
create_opts.retry_delay_seconds = std.math.cast(u32, n) orelse return res.fail(.INVALID_REQUEST, "retryDelaySeconds must be non-negative");
|
||||
}
|
||||
if (req.payloadInt("timeoutSeconds")) |n| {
|
||||
create_opts.timeout_seconds = std.math.cast(u32, n) orelse return res.fail(.INVALID_REQUEST, "timeoutSeconds must be non-negative");
|
||||
}
|
||||
create_opts.load_level = if (req.payloadString("loadLevel")) |l|
|
||||
LoadLevel.parse(l) orelse return res.failFmt(.INVALID_REQUEST, "Invalid load level: '{s}'. Valid values are: high, medium, low", .{l})
|
||||
else
|
||||
|
||||
Reference in new issue
Block a user