Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962const std = @import("std");const runtime = @import("../runtime.zig");const wap = @import("wap");const mem = std.mem;const json = std.json;const Allocator = std.mem.Allocator;
const db = @import("../db/sqlite.zig");const routing = @import("routing.zig");const uuid_util = @import("../utilities/uuid.zig");const time_util = @import("../utilities/time.zig");const state_message = @import("../utilities/state_message.zig");const task_workers = @import("../task_workers.zig");const history = @import("history.zig");const orchestration = @import("../orchestration.zig");
// ===== typed bodies — mirror python's TaskRunCreate / set_state =====
const StateCreate = struct { type: []const u8, name: ?[]const u8 = null, message: ?[]const u8 = null, data: ?json.Value = null, state_details: ?json.Value = null, id: ?[]const u8 = null, timestamp: ?[]const u8 = null,};
const TaskRunCreateBody = struct { task_key: []const u8, dynamic_key: []const u8, flow_run_id: ?[]const u8 = null, name: ?[]const u8 = null, id: ?[]const u8 = null, state: ?StateCreate = null, cache_key: ?[]const u8 = null, cache_expiration: ?[]const u8 = null, task_version: ?[]const u8 = null, empirical_policy: ?json.Value = null, tags: ?json.Value = null, labels: ?json.Value = null, task_inputs: ?json.Value = null,};
const SetStateInputBody = struct { state: StateCreate, force: bool = false,};
fn stringifyValue(alloc: Allocator, value: json.Value) ![]const u8 { var buf: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &buf.writer }; try jw.write(value); return buf.toOwnedSlice();}
fn stringifyOrDefault(alloc: Allocator, value: ?json.Value, default_literal: []const u8) []const u8 { if (value) |v| return stringifyValue(alloc, v) catch default_literal; return default_literal;}
fn sendValidationError(res: *wap.Response, detail: []const u8) !void { _ = res.setStatus(.unprocessable_entity); try res.writeJson(.{ .detail = detail });}
// POST /task_runs/ - create task run// POST /task_runs/filter - list task runs// GET /task_runs/{id} - read task run// POST /task_runs/{id}/set_state - set statepub fn handle(req: *wap.Request, res: *wap.Response) !void { const target = req.path; const method = @tagName(req.method);
if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/filter")) { try filter(req, res); return; } if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/count")) { try countTaskRuns(req, res); return; } if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/paginate")) { try paginateTaskRuns(req, res); return; } if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/history")) { try historyTaskRuns(req, res); return; }
if (mem.eql(u8, method, "POST") and (mem.eql(u8, target, "/task_runs/") or mem.eql(u8, target, "/api/task_runs/"))) { try create(req, res); return; }
if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/set_state")) { const id = routing.extractId(target, "/task_runs/", "/set_state") orelse routing.extractId(target, "/api/task_runs/", "/set_state"); if (id) |task_run_id| { try setState(req, res, task_run_id); return; } }
if (mem.eql(u8, method, "GET")) { const id = routing.extractIdAfter(target, "/task_runs/") orelse routing.extractIdAfter(target, "/api/task_runs/"); if (id) |task_run_id| { try read(res, task_run_id); return; } }
if (mem.eql(u8, method, "PATCH")) { const id = routing.extractIdAfter(target, "/task_runs/") orelse routing.extractIdAfter(target, "/api/task_runs/"); if (id) |task_run_id| { try patchTaskRun(req, res, task_run_id); return; } }
if (mem.eql(u8, method, "DELETE")) { const id = routing.extractIdAfter(target, "/task_runs/") orelse routing.extractIdAfter(target, "/api/task_runs/"); if (id) |task_run_id| { try deleteTaskRun(res, task_run_id); return; } }
_ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "not found" });}
const TaskRunUpdateBody = struct { name: ?[]const u8 = null,};
/// `PATCH /task_runs/{id}` — python's TaskRunUpdate only declares `name`./// 204 on success, 404 if missing.fn patchTaskRun(req: *wap.Request, res: *wap.Response, task_run_id: []const u8) !void { const body = req.parseJson(TaskRunUpdateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; const new_name = body.name orelse { // No-op update: still need to confirm the row exists. const alloc = req.arena; if ((try db.getTaskRun(alloc, task_run_id)) == null) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Task run not found" }); return; } try res.sendEmpty(.no_content); return; };
var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); const updated = db.task_runs.updateName(task_run_id, new_name, now) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "update failed" }); return; }; if (!updated) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Task run not found" }); return; } try res.sendEmpty(.no_content);}
/// `DELETE /task_runs/{id}` — 204 on success, 404 if missing.fn deleteTaskRun(res: *wap.Response, task_run_id: []const u8) !void { const deleted = db.task_runs.delete(task_run_id) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "delete failed" }); return; }; if (!deleted) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Task run not found" }); return; } try res.sendEmpty(.no_content);}
fn create(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
const body = req.parseJson(TaskRunCreateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; };
const name = body.name orelse routing.generateRunName(runtime.appIo(), alloc);
// check for existing task run (idempotency) if (try db.getTaskRunByKey(alloc, body.flow_run_id, body.task_key, body.dynamic_key)) |existing| { const resp = writeTaskRun(alloc, existing, null) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); return; }
// state — type/name default to PENDING/Pending when not provided var state_type: []const u8 = "PENDING"; var state_name: []const u8 = "Pending"; var extras = db.task_runs.StateExtras{}; if (body.state) |s| { state_type = s.type; if (s.name) |n| state_name = n; extras = extractStateExtras(alloc, s) catch .{}; }
// JSON-blob fields stringify once for storage. tags defaults to "[]", // labels/empirical_policy/task_inputs to "{}", matching python schema defaults. const empirical_policy = stringifyOrDefault(alloc, body.empirical_policy, "{}"); const task_inputs = stringifyOrDefault(alloc, body.task_inputs, "{}"); const tags = stringifyOrDefault(alloc, body.tags, "[]"); const labels = stringifyOrDefault(alloc, body.labels, "{}");
var new_id_buf: [36]u8 = undefined; const new_id = uuid_util.generate(runtime.appIo(), &new_id_buf); var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); var state_id_buf: [36]u8 = undefined; const state_id = uuid_util.generate(runtime.appIo(), &state_id_buf);
// Python routes creation-with-state through set_task_run_state, so the // global transforms run at create time too. var create_bookkeeping = orchestration.TransitionContext{ .current_state_type = null, .current_state_timestamp = null, .start_time = null, .end_time = null, .run_count = 0, .total_run_time = 0.0, .proposed_state_type = orchestration.StateType.fromString(state_type), .proposed_state_timestamp = now, .proposed_scheduled_time = try scheduledTimeFromExtras(alloc, extras), }; orchestration.applyBookkeeping(&create_bookkeeping);
db.insertTaskRun(new_id, body.flow_run_id, name, body.task_key, body.dynamic_key, state_type, state_name, now, state_id, extras, .{ .task_version = body.task_version, .empirical_policy = empirical_policy, .task_inputs = task_inputs, .tags = tags, .labels = labels, .cache_key = body.cache_key, .cache_expiration = body.cache_expiration, .expected_start_time = create_bookkeeping.new_expected_start_time, .start_time = create_bookkeeping.new_start_time, .run_count = create_bookkeeping.new_run_count, }) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "insert failed" }); return; };
const run = db.TaskRunRow{ .id = new_id, .created = now, .updated = now, .name = name, .flow_run_id = body.flow_run_id orelse "", .task_key = body.task_key, .dynamic_key = body.dynamic_key, .state_type = state_type, .state_name = state_name, .state_timestamp = now, .state_message = extras.message, .state_details = extras.state_details orelse "{}", .state_data = extras.data, .tags = tags, .labels = labels, .task_version = body.task_version, .empirical_policy = empirical_policy, .task_inputs = task_inputs, .cache_key = body.cache_key, .cache_expiration = body.cache_expiration, .run_count = 0, .flow_run_run_count = 0, .expected_start_time = null, .next_scheduled_start_time = null, .start_time = null, .end_time = null, .total_run_time = 0.0, };
const resp = writeTaskRun(alloc, run, state_id) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; };
// Background-task enqueue hook: SCHEDULED + state_details.deferred=true // means this is a `task.delay()` submission. if (std.mem.eql(u8, state_type, "SCHEDULED") and isDeferredExtras(extras)) { task_workers.enqueue(body.task_key, new_id, resp); }
_ = res.setStatus(.created); _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp);}
/// `state_details.scheduled_time`, read back out of the stringified extras.fn scheduledTimeFromExtras(alloc: Allocator, extras: db.task_runs.StateExtras) !?[]const u8 { const sd = extras.state_details orelse return null; const parsed = json.parseFromSlice(json.Value, alloc, sd, .{ .ignore_unknown_fields = true }) catch |err| switch (err) { error.OutOfMemory => return err, else => return null, }; if (parsed.value != .object) return null; const scheduled = parsed.value.object.get("scheduled_time") orelse return null; if (scheduled != .string or scheduled.string.len == 0) return null; return scheduled.string;}
fn isDeferredExtras(extras: db.task_runs.StateExtras) bool { const sd = extras.state_details orelse return false; return std.mem.indexOf(u8, sd, "\"deferred\":true") != null or std.mem.indexOf(u8, sd, "\"deferred\": true") != null;}
fn read(res: *wap.Response, id: []const u8) !void { const alloc = res.arena;
const run = try db.getTaskRun(alloc, id) orelse { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "task run not found" }); return; };
const resp = writeTaskRun(alloc, run, null) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp);}
fn setState(req: *wap.Request, res: *wap.Response, id: []const u8) !void { const alloc = req.arena;
const body = req.parseJson(SetStateInputBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; };
const state = body.state; const state_type = state.type; const state_name = state.name orelse "Pending"; var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); var state_id_buf: [36]u8 = undefined; const state_id = uuid_util.generate(runtime.appIo(), &state_id_buf);
const extras = extractStateExtras(alloc, state) catch db.task_runs.StateExtras{};
// Same global bookkeeping transforms the flow-run transition applies: // start_time on first RUNNING, end_time on terminal, run_count and // total_run_time accumulation. Without these, /task_runs/filter's // start_time window (what the dashboard scopes every tile by) never // matches an API-orchestrated task run. const current = try db.getTaskRun(alloc, id); var bookkeeping = orchestration.TransitionContext{ .current_state_type = if (current) |run| if (run.state_type.len > 0) orchestration.StateType.fromString(run.state_type) else null else null, .current_state_timestamp = if (current) |run| if (run.state_timestamp.len > 0) run.state_timestamp else null else null, .start_time = if (current) |run| run.start_time else null, .end_time = if (current) |run| run.end_time else null, .run_count = if (current) |run| run.run_count else 0, .total_run_time = if (current) |run| run.total_run_time else 0.0, .expected_start_time = if (current) |run| run.expected_start_time else null, .proposed_state_type = orchestration.StateType.fromString(state_type), .proposed_state_timestamp = now, .proposed_scheduled_time = try scheduledTimeFromExtras(alloc, extras), }; orchestration.applyBookkeeping(&bookkeeping);
db.task_runs.setStateWithDetails(id, state_id, state_type, state_name, now, extras, .{ .expected_start_time = bookkeeping.new_expected_start_time, .start_time = bookkeeping.new_start_time, .end_time = bookkeeping.new_end_time, .run_count = bookkeeping.new_run_count, .total_run_time = bookkeeping.new_total_run_time, }) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "update failed" }); return; };
try res.writeJson(.{ .status = "ACCEPT", .details = .{}, .state = .{ .type = state_type, .name = state_name, .timestamp = now, .id = state_id, .message = extras.message, .state_details = json.parseFromSliceLeaky(json.Value, alloc, extras.state_details orelse "{}", .{}) catch json.Value{ .object = .{} }, .data = if (extras.data) |d| (json.parseFromSliceLeaky(json.Value, alloc, d, .{}) catch json.Value.null) else json.Value.null, }, });}
/// Extract state.message (truncated) and stringify state.state_details + state.data/// for storage. Allocations live for the request arena.fn extractStateExtras(alloc: Allocator, state: StateCreate) !db.task_runs.StateExtras { var extras = db.task_runs.StateExtras{};
if (state.message) |m| { if (m.len > 0) { const trimmed = try state_message.truncate(alloc, m, state_message.maxLength()); extras.message = if (trimmed.owned) trimmed.text else try alloc.dupe(u8, trimmed.text); } }
if (state.state_details) |sd| { if (sd == .object) { extras.state_details = try stringifyValue(alloc, sd); } }
if (state.data) |d| { if (d != .null) { extras.data = try stringifyValue(alloc, d); } }
return extras;}
/// `POST /task_runs/count` — body is the unified filter envelope/// (`flows`, `flow_runs`, `task_runs`, `deployments`), matching python's/// `count_task_runs`. Sub-filters AND together; an absent one never narrows.fn countTaskRuns(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
var opts: db.task_runs.FilterOpts = .{}; parseFilterBody(alloc, req.body, &opts, res) catch |err| switch (err) { error.InvalidFilter => return, else => return err, };
const n = db.task_runs.countFiltered(alloc, opts) catch |err| switch (err) { error.InvalidFilterValue => return sendValidationError(res, "filter value contains disallowed characters"), else => { _ = res.setStatus(.internal_server_error); return res.writeJson(.{ .detail = "database error" }); }, }; try res.writeJson(n);}
/// Parse the shared filter envelope into `FilterOpts`. On a malformed body the/// error response is already written when `error.InvalidFilter` is returned.fn parseFilterBody( alloc: Allocator, body: []const u8, opts: *db.task_runs.FilterOpts, res: *wap.Response,) !void { if (body.len == 0) return; const parsed = json.parseFromSlice(json.Value, alloc, body, .{ .ignore_unknown_fields = true }) catch { try sendValidationError(res, "invalid json"); return error.InvalidFilter; }; if (parsed.value != .object) { try sendValidationError(res, "body must be an object"); return error.InvalidFilter; } const root = parsed.value.object;
if (root.get("task_runs")) |tr| if (tr == .object) { const o = tr.object; if (o.get("id")) |v| try readAny(alloc, v, res, "task_runs.id", &opts.ids, &opts.ids_present); if (o.get("name")) |v| if (v == .object) { try readAny(alloc, v, res, "task_runs.name", &opts.names, &opts.names_present); if (v.object.get("like_")) |like| opts.name_like = try readString(like, res, "task_runs.name.like_"); }; if (o.get("tags")) |v| if (v == .object) { var present = false; if (v.object.get("all_")) |all| try readAnyList(alloc, all, res, "task_runs.tags.all_", &opts.tags_all, &present); opts.tags_is_null = try readBool(v.object.get("is_null_"), res, "task_runs.tags.is_null_"); }; if (o.get("flow_run_id")) |v| if (v == .object) { try readAny(alloc, v, res, "task_runs.flow_run_id", &opts.flow_run_ids, &opts.flow_run_ids_present); const is_null = try readBool(v.object.get("is_null_"), res, "task_runs.flow_run_id.is_null_"); // python's TaskRunFilterFlowRunId defaults is_null_ to False, so an // `any_`-less flow_run_id filter means "has a flow run". opts.flow_run_id_is_null = if (is_null) |b| b else if (opts.flow_run_ids_present) null else false; }; if (o.get("state")) |state| if (state == .object) { if (state.object.get("type")) |t| if (t == .object) { try readAny(alloc, t, res, "task_runs.state.type", &opts.state_types, &opts.state_types_present); var not_present = false; if (t.object.get("not_any_")) |n| try readAnyList(alloc, n, res, "task_runs.state.type.not_any_", &opts.not_state_types, ¬_present); }; if (state.object.get("name")) |n| if (n == .object) { try readAny(alloc, n, res, "task_runs.state.name", &opts.state_names, &opts.state_names_present); }; }; if (o.get("start_time")) |v| { try readTimestampRange(v, res, "task_runs.start_time", &opts.start_time_after, &opts.start_time_before); if (v == .object) opts.start_time_is_null = try readBool(v.object.get("is_null_"), res, "task_runs.start_time.is_null_"); } if (o.get("end_time")) |v| { try readTimestampRange(v, res, "task_runs.end_time", &opts.end_time_after, &opts.end_time_before); if (v == .object) opts.end_time_is_null = try readBool(v.object.get("is_null_"), res, "task_runs.end_time.is_null_"); } if (o.get("expected_start_time")) |v| { try readTimestampRange(v, res, "task_runs.expected_start_time", &opts.expected_start_time_after, &opts.expected_start_time_before); } if (o.get("subflow_runs")) |v| if (v == .object) { opts.subflow_runs_exists = try readBool(v.object.get("exists_"), res, "task_runs.subflow_runs.exists_"); }; };
if (root.get("flow_runs")) |fr| if (fr == .object) { const o = fr.object; if (o.get("id")) |v| try readAny(alloc, v, res, "flow_runs.id", &opts.parent_flow_run_ids, &opts.parent_flow_run_ids_present); if (o.get("deployment_id")) |v| try readAny(alloc, v, res, "flow_runs.deployment_id", &opts.deployment_ids, &opts.deployment_ids_present); if (o.get("parent_task_run_id")) |v| if (v == .object) { opts.flow_run_parent_task_run_id_is_null = try readBool(v.object.get("is_null_"), res, "flow_runs.parent_task_run_id.is_null_"); }; if (o.get("state")) |state| if (state == .object) { if (state.object.get("type")) |t| if (t == .object) { try readAny(alloc, t, res, "flow_runs.state.type", &opts.flow_run_state_types, &opts.flow_run_state_types_present); }; if (state.object.get("name")) |n| if (n == .object) { try readAny(alloc, n, res, "flow_runs.state.name", &opts.flow_run_state_names, &opts.flow_run_state_names_present); }; }; };
if (root.get("flows")) |flows| if (flows == .object) { if (flows.object.get("id")) |v| try readAny(alloc, v, res, "flows.id", &opts.flow_ids, &opts.flow_ids_present); };
if (root.get("deployments")) |deployments| if (deployments == .object) { if (deployments.object.get("id")) |v| try readAny(alloc, v, res, "deployments.id", &opts.deployment_ids, &opts.deployment_ids_present); };
if (root.get("sort")) |sort| switch (sort) { .string => |s| opts.sort = s, else => {}, };}
/// Read `{any_: [...]}` (or the `{eq_: "..."}` shape some clients send) into/// `out`. `present` distinguishes "no predicate" from "matches nothing".fn readAny( alloc: Allocator, value: json.Value, res: *wap.Response, label: []const u8, out: *[]const []const u8, present: *bool,) !void { if (value != .object) return; if (value.object.get("any_")) |any| return readAnyList(alloc, any, res, label, out, present); if (value.object.get("eq_")) |eq| switch (eq) { .string => |s| { out.* = try alloc.dupe([]const u8, &.{s}); present.* = true; }, else => { try sendValidationError(res, label); return error.InvalidFilter; }, };}
fn readAnyList( alloc: Allocator, any: json.Value, res: *wap.Response, label: []const u8, out: *[]const []const u8, present: *bool,) !void { if (any == .null) return; if (any != .array) { try sendValidationError(res, label); return error.InvalidFilter; } var list = try alloc.alloc([]const u8, any.array.items.len); for (any.array.items, 0..) |item, i| { if (item != .string) { try sendValidationError(res, label); return error.InvalidFilter; } list[i] = item.string; } out.* = list; present.* = true;}
fn readString(value: json.Value, res: *wap.Response, label: []const u8) ![]const u8 { return switch (value) { .string => |s| s, else => { try sendValidationError(res, label); return error.InvalidFilter; }, };}
fn readBool(value: ?json.Value, res: *wap.Response, label: []const u8) !?bool { const v = value orelse return null; return switch (v) { .bool => |b| b, .null => null, else => { try sendValidationError(res, label); return error.InvalidFilter; }, };}
fn readTimestampRange( value: json.Value, res: *wap.Response, label: []const u8, after: *?[]const u8, before: *?[]const u8,) !void { if (value != .object) return; if (value.object.get("after_")) |v| if (v != .null) { after.* = try readString(v, res, label); }; if (value.object.get("before_")) |v| if (v != .null) { before.* = try readString(v, res, label); };}
const PaginateBody = struct { limit: ?i64 = null, page: ?i64 = null, flows: ?json.Value = null, flow_runs: ?json.Value = null, task_runs: ?json.Value = null, deployments: ?json.Value = null, work_pools: ?json.Value = null, sort: ?[]const u8 = null,};
/// `POST /task_runs/paginate` — `{results, count, limit, pages, page}`.fn paginateTaskRuns(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
var limit: i64 = 50; var page: i64 = 1; if (req.body.len > 0) { if (req.parseJson(PaginateBody)) |body| { if (body.limit) |l| limit = l; if (body.page) |p| page = p; } else |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; } } if (page < 1) page = 1; if (limit < 1) limit = 1; if (limit > 1000) limit = 1000; const offset: i64 = (page - 1) * limit;
var opts: db.task_runs.FilterOpts = .{}; parseFilterBody(alloc, req.body, &opts, res) catch |err| switch (err) { error.InvalidFilter => return, else => return err, }; opts.limit = @intCast(limit); opts.offset = @intCast(@max(offset, 0));
const runs = db.task_runs.filter(alloc, opts) catch |err| switch (err) { error.InvalidFilterValue => return sendValidationError(res, "filter value contains disallowed characters"), else => { _ = res.setStatus(.internal_server_error); return res.writeJson(.{ .detail = "database error" }); }, }; const total = try db.task_runs.countFiltered(alloc, opts);
const pages = if (limit > 0) @divFloor(total + limit - 1, limit) else 0;
var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try jw.beginObject(); try jw.objectField("results"); try jw.beginArray(); for (runs) |run| try writeTaskRunObject(&jw, run, null); try jw.endArray(); try jw.objectField("count"); try jw.write(total); try jw.objectField("limit"); try jw.write(limit); try jw.objectField("pages"); try jw.write(pages); try jw.objectField("page"); try jw.write(page); try jw.endObject();
_ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice());}
fn filter(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
var opts: db.task_runs.FilterOpts = .{ .limit = 50 }; parseFilterBody(alloc, req.body, &opts, res) catch |err| switch (err) { error.InvalidFilter => return, else => return err, };
if (req.body.len > 0) { if (json.parseFromSlice(json.Value, alloc, req.body, .{ .ignore_unknown_fields = true })) |parsed| { if (parsed.value == .object) { if (parsed.value.object.get("limit")) |l| switch (l) { .integer => |i| { if (i < 0) return sendValidationError(res, "limit must be non-negative"); opts.limit = @intCast(i); }, else => {}, }; if (parsed.value.object.get("offset")) |o| switch (o) { .integer => |i| { if (i < 0) return sendValidationError(res, "offset must be non-negative"); opts.offset = @intCast(i); }, else => {}, }; } } else |parse_err| { if (parse_err == error.OutOfMemory) return parse_err; } }
const runs = db.task_runs.filter(alloc, opts) catch |err| switch (err) { error.InvalidFilterValue => return sendValidationError(res, "filter value contains disallowed characters"), error.LimitTooLarge => return sendValidationError(res, "limit must be <= 1000"), else => { _ = res.setStatus(.internal_server_error); return res.writeJson(.{ .detail = "database error" }); }, };
var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer };
jw.beginArray() catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; };
for (runs) |run| { try writeTaskRunObject(&jw, run, null); }
try jw.endArray();
_ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice());}
const HistoryBody = struct { history_start: []const u8, history_end: []const u8, history_interval_seconds: f64, flows: ?json.Value = null, flow_runs: ?json.Value = null, task_runs: ?json.Value = null, deployments: ?json.Value = null, work_pools: ?json.Value = null, work_queues: ?json.Value = null,};
/// `POST /task_runs/history` — bucketed (state_type, state_name) counts/// per interval. Mirrors python's HistoryResponse shape;/// `sum_estimated_run_time` / `sum_estimated_lateness` are 0.0 since we/// don't track those columns yet.fn historyTaskRuns(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
const body = req.parseJson(HistoryBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; if (body.history_interval_seconds < 1) { return sendValidationError(res, "History interval must not be less than 1 second."); }
var opts: db.task_runs.FilterOpts = .{}; parseFilterBody(alloc, req.body, &opts, res) catch |err| switch (err) { error.InvalidFilter => return, else => return err, }; const predicates = db.task_runs.filterPredicateSql(alloc, opts) catch |err| switch (err) { error.InvalidFilterValue => return sendValidationError(res, "filter value contains disallowed characters"), else => return err, };
try history.writeHistoryBuckets(alloc, res, .task_run, body.history_start, body.history_end, body.history_interval_seconds, predicates);}
fn writeTaskRun(alloc: std.mem.Allocator, run: db.TaskRunRow, state_id: ?[]const u8) ![]const u8 { var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try writeTaskRunObject(&jw, run, state_id); return output.toOwnedSlice();}
fn writeTaskRunObject(jw: *json.Stringify, run: db.TaskRunRow, state_id: ?[]const u8) !void { try jw.beginObject();
try jw.objectField("id"); try jw.write(run.id); try jw.objectField("created"); try jw.write(run.created); try jw.objectField("updated"); try jw.write(run.updated); try jw.objectField("name"); try jw.write(run.name); try jw.objectField("flow_run_id"); if (run.flow_run_id.len > 0) try jw.write(run.flow_run_id) else try jw.write(null); try jw.objectField("task_key"); try jw.write(run.task_key); try jw.objectField("dynamic_key"); try jw.write(run.dynamic_key); try jw.objectField("cache_key"); try jw.write(run.cache_key); try jw.objectField("task_version"); try jw.write(run.task_version); try jw.objectField("empirical_policy"); try jw.beginWriteRaw(); try jw.writer.writeAll(if (run.empirical_policy.len > 0) run.empirical_policy else "{}"); jw.endWriteRaw(); try jw.objectField("task_inputs"); try jw.beginWriteRaw(); try jw.writer.writeAll(if (run.task_inputs.len > 0) run.task_inputs else "{}"); jw.endWriteRaw(); try jw.objectField("state_type"); try jw.write(run.state_type); try jw.objectField("state_name"); try jw.write(run.state_name); try jw.objectField("state"); try jw.beginObject(); try jw.objectField("type"); try jw.write(run.state_type); try jw.objectField("name"); try jw.write(run.state_name); try jw.objectField("timestamp"); try jw.write(run.state_timestamp); if (state_id) |sid| { try jw.objectField("id"); try jw.write(sid); } try jw.objectField("message"); if (run.state_message) |m| try jw.write(m) else try jw.write(null); try jw.objectField("state_details"); try jw.beginWriteRaw(); try jw.writer.writeAll(if (run.state_details.len > 0) run.state_details else "{}"); jw.endWriteRaw(); try jw.objectField("data"); if (run.state_data) |d| { try jw.beginWriteRaw(); try jw.writer.writeAll(d); jw.endWriteRaw(); } else { try jw.write(null); } try jw.endObject();
try jw.objectField("tags"); try jw.beginWriteRaw(); try jw.writer.writeAll(if (run.tags.len > 0) run.tags else "[]"); jw.endWriteRaw();
try jw.objectField("labels"); try jw.beginWriteRaw(); try jw.writer.writeAll(if (run.labels.len > 0) run.labels else "{}"); jw.endWriteRaw();
try jw.objectField("cache_expiration"); try jw.write(run.cache_expiration);
try jw.objectField("run_count"); try jw.write(run.run_count);
try jw.objectField("flow_run_run_count"); try jw.write(run.flow_run_run_count);
try jw.objectField("expected_start_time"); try jw.write(run.expected_start_time);
try jw.objectField("next_scheduled_start_time"); try jw.write(run.next_scheduled_start_time);
try jw.objectField("start_time"); try jw.write(run.start_time);
try jw.objectField("end_time"); try jw.write(run.end_time);
try jw.objectField("total_run_time"); try jw.write(run.total_run_time);
const now_us = time_util.microTimestamp(runtime.appIo());
try jw.objectField("estimated_run_time"); try jw.write(orchestration.estimatedRunTime( run.state_type, run.state_timestamp, run.total_run_time, now_us, ));
try jw.objectField("estimated_start_time_delta"); try jw.write(orchestration.estimatedStartTimeDelta( run.state_type, run.expected_start_time, run.start_time, now_us, ));
try jw.endObject();}