Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577const 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 uuid_util = @import("../utilities/uuid.zig");const time_util = @import("../utilities/time.zig");
// ===== typed bodies — mirror python's ArtifactCreate / Update =====
const ArtifactCreateBody = struct { key: ?[]const u8 = null, task_run_id: ?[]const u8 = null, flow_run_id: ?[]const u8 = null, type: ?[]const u8 = null, data: ?json.Value = null, description: ?[]const u8 = null, metadata_: ?json.Value = null,};
const ArtifactUpdateBody = struct { data: ?json.Value = null, description: ?[]const u8 = null,};
const FilterBody = struct { limit: ?usize = null, offset: ?usize = null, sort: ?[]const u8 = null, artifacts: ?json.Value = null, flow_runs: ?json.Value = null, task_runs: ?json.Value = null, deployments: ?json.Value = null, flows: ?json.Value = null,};
fn stringifyValue(alloc: Allocator, value: json.Value) ![]const u8 { var buf: std.Io.Writer.Allocating = .init(alloc); errdefer buf.deinit(); var jw: json.Stringify = .{ .writer = &buf.writer }; try jw.write(value); return buf.toOwnedSlice();}
fn stringifyOrNull(alloc: Allocator, value: ?json.Value) !?[]const u8 { if (value) |v| return try stringifyValue(alloc, v); return null;}
fn sendError(res: *wap.Response, status: std.http.Status, detail: []const u8) !void { _ = res.setStatus(status); try res.writeJson(.{ .detail = detail });}
fn sendValidationError(res: *wap.Response, detail: []const u8) !void { try sendError(res, .unprocessable_entity, detail);}
pub fn handle(req: *wap.Request, res: *wap.Response) !void { const target = req.path; const method = @tagName(req.method);
// POST /artifacts/latest/filter if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/latest/filter")) { try filterLatest(req, res); return; }
// POST /artifacts/latest/count if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/latest/count")) { try countLatest(req, res); return; }
// POST /artifacts/filter if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/filter")) { try filterArtifacts(req, res); return; }
// POST /artifacts/count if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/count")) { try countArtifacts(req, res); return; }
// POST /artifacts/ — create if (mem.eql(u8, method, "POST") and (mem.eql(u8, target, "/artifacts/") or mem.eql(u8, target, "/api/artifacts/"))) { try createArtifact(req, res); return; }
if (mem.eql(u8, method, "GET") and mem.endsWith(u8, target, "/latest")) { const key = extractKeyBeforeLatest(target) orelse { try sendError(res, .bad_request, "key required"); return; }; try getLatestByKey(res, key); return; }
if (mem.eql(u8, method, "GET")) { const id = extractId(target) orelse { try sendError(res, .bad_request, "artifact id required"); return; }; try getById(res, id); return; }
if (mem.eql(u8, method, "PATCH")) { const id = extractId(target) orelse { try sendError(res, .bad_request, "artifact id required"); return; }; try updateById(req, res, id); return; }
if (mem.eql(u8, method, "DELETE")) { const id = extractId(target) orelse { try sendError(res, .bad_request, "artifact id required"); return; }; try deleteById(res, id); return; }
try sendError(res, .not_implemented, "not implemented");}
fn extractId(target: []const u8) ?[]const u8 { const prefix = if (mem.startsWith(u8, target, "/api/artifacts/")) "/api/artifacts/" else "/artifacts/"; if (target.len > prefix.len) { const remainder = target[prefix.len..]; // Filter / count / latest endpoints already matched above; whatever // is left is treated as the id. return remainder; } return null;}
fn extractKeyBeforeLatest(target: []const u8) ?[]const u8 { const prefix = if (mem.startsWith(u8, target, "/api/artifacts/")) "/api/artifacts/" else "/artifacts/"; if (target.len <= prefix.len) return null; const remainder = target[prefix.len..]; // remainder is "{key}/latest" — strip the suffix. if (!mem.endsWith(u8, remainder, "/latest")) return null; const key = remainder[0 .. remainder.len - "/latest".len]; if (key.len == 0) return null; return key;}
fn createArtifact(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
const body = req.parseJson(ArtifactCreateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; };
const data_json = try stringifyOrNull(alloc, body.data); const metadata_json = try stringifyOrNull(alloc, body.metadata_);
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);
const params = db.artifacts.InsertParams{ .key = body.key, .task_run_id = body.task_run_id, .flow_run_id = body.flow_run_id, .type = body.type, .data = data_json, .description = body.description, .metadata_ = metadata_json, };
db.artifacts.insert(new_id, now, params) catch { try sendError(res, .internal_server_error, "insert failed"); return; };
if (body.key) |k| { var coll_id_buf: [36]u8 = undefined; const coll_id = uuid_util.generate(runtime.appIo(), &coll_id_buf); try db.artifacts.upsertCollection(coll_id, now, k, new_id, params); }
const row = db.artifacts.ArtifactRow{ .id = new_id, .created = now, .updated = now, .key = body.key, .task_run_id = body.task_run_id, .flow_run_id = body.flow_run_id, .type = body.type, .data = data_json, .description = body.description, .metadata_ = metadata_json, }; const resp = writeArtifact(alloc, row) catch { try sendError(res, .internal_server_error, "serialize error"); return; }; _ = res.setStatus(.created); _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp);}
fn getById(res: *wap.Response, id: []const u8) !void { const alloc = res.arena;
if (try db.artifacts.getById(alloc, id)) |row| { const resp = writeArtifact(alloc, row) catch { try sendError(res, .internal_server_error, "serialize error"); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); } else { try sendError(res, .not_found, "Artifact not found."); }}
fn getLatestByKey(res: *wap.Response, key: []const u8) !void { const alloc = res.arena;
if (try db.artifacts.getLatestByKey(alloc, key)) |row| { const resp = writeCollection(alloc, row) catch { try sendError(res, .internal_server_error, "serialize error"); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); } else { try sendError(res, .not_found, "Artifact not found."); }}
fn updateById(req: *wap.Request, res: *wap.Response, id: []const u8) !void { const alloc = req.arena;
const body = req.parseJson(ArtifactUpdateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; };
const data_json = try stringifyOrNull(alloc, body.data);
var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf);
const did_update = db.artifacts.updateById(id, data_json, body.description, now) catch { try sendError(res, .internal_server_error, "update failed"); return; };
if (!did_update) { try sendError(res, .not_found, "Artifact not found."); return; } try res.sendEmpty(.no_content);}
fn deleteById(res: *wap.Response, id: []const u8) !void { const deleted = db.artifacts.deleteById(id) catch { try sendError(res, .internal_server_error, "delete failed"); return; }; if (!deleted) { try sendError(res, .not_found, "Artifact not found."); return; } try res.sendEmpty(.no_content);}
fn filterArtifacts(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
var limit: usize = 200; var offset: usize = 0; var sort: db.artifacts.Sort = .id_desc; var filter: db.artifacts.ArtifactFilter = .{};
if (req.body.len > 0) { if (req.parseJson(FilterBody)) |body| { if (body.limit) |l| limit = l; if (body.offset) |o| offset = o; if (body.sort) |s| sort = db.artifacts.Sort.fromString(s); if (body.artifacts) |af| try parseArtifactFilter(alloc, af, &filter); } else |err| { if (err == error.OutOfMemory) return err; } }
const rows = db.artifacts.listFiltered(alloc, filter, sort, limit, offset) catch { try sendError(res, .internal_server_error, "database error"); return; };
var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try jw.beginArray(); for (rows) |row| try writeArtifactObject(&jw, row); try jw.endArray(); _ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice());}
fn filterLatest(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
var limit: usize = 200; var offset: usize = 0; var sort: db.artifacts.Sort = .id_desc; var filter: db.artifacts.ArtifactCollectionFilter = .{};
if (req.body.len > 0) { if (req.parseJson(FilterBody)) |body| { if (body.limit) |l| limit = l; if (body.offset) |o| offset = o; if (body.sort) |s| sort = db.artifacts.Sort.fromString(s); if (body.artifacts) |af| try parseCollectionFilter(alloc, af, &filter); } else |err| { if (err == error.OutOfMemory) return err; } }
const rows = db.artifacts.listCollectionFiltered(alloc, filter, sort, limit, offset) catch { try sendError(res, .internal_server_error, "database error"); return; };
var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try jw.beginArray(); for (rows) |row| try writeCollectionObject(&jw, row); try jw.endArray(); _ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice());}
fn countArtifacts(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
var filter: db.artifacts.ArtifactFilter = .{}; if (req.body.len > 0) { if (req.parseJson(FilterBody)) |body| { if (body.artifacts) |af| try parseArtifactFilter(alloc, af, &filter); } else |err| { if (err == error.OutOfMemory) return err; } } const cnt = try db.artifacts.countFilter(alloc, filter); try res.writeJson(cnt);}
fn countLatest(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
var filter: db.artifacts.ArtifactCollectionFilter = .{}; if (req.body.len > 0) { if (req.parseJson(FilterBody)) |body| { if (body.artifacts) |af| try parseCollectionFilter(alloc, af, &filter); } else |err| { if (err == error.OutOfMemory) return err; } } const cnt = try db.artifacts.countCollectionFilter(alloc, filter); try res.writeJson(cnt);}
// ============================================================// Filter parsing (python's nested {any_:, not_any_:, like_:} shape)// ============================================================
fn parseStringArray(alloc: std.mem.Allocator, val: json.Value) !?[]const []const u8 { if (val != .array) return null; var list = std.ArrayListUnmanaged([]const u8).empty; defer list.deinit(alloc); for (val.array.items) |item| { if (item == .string) try list.append(alloc, item.string); } if (list.items.len == 0) return null; return try list.toOwnedSlice(alloc);}
fn anyFromFilter(alloc: std.mem.Allocator, sub: json.Value) !?[]const []const u8 { if (sub != .object) return null; if (sub.object.get("any_")) |v| return try parseStringArray(alloc, v); return null;}
fn notAnyFromFilter(alloc: std.mem.Allocator, sub: json.Value) !?[]const []const u8 { if (sub != .object) return null; if (sub.object.get("not_any_")) |v| return try parseStringArray(alloc, v); return null;}
fn likeFromFilter(sub: json.Value) ?[]const u8 { if (sub != .object) return null; if (sub.object.get("like_")) |v| { return switch (v) { .string => |s| s, else => null, }; } return null;}
fn existsFromFilter(sub: json.Value) ?bool { if (sub != .object) return null; if (sub.object.get("exists_")) |v| { return switch (v) { .bool => |b| b, else => null, }; } return null;}
fn parseArtifactFilter(alloc: std.mem.Allocator, af: json.Value, out: *db.artifacts.ArtifactFilter) !void { if (af != .object) return; const obj = af.object; if (obj.get("id")) |v| { out.ids_any = try anyFromFilter(alloc, v); out.ids_not_any = try notAnyFromFilter(alloc, v); } if (obj.get("key")) |v| { out.keys_any = try anyFromFilter(alloc, v); out.key_like = likeFromFilter(v); out.key_exists = existsFromFilter(v); } if (obj.get("flow_run_id")) |v| { out.flow_run_ids_any = try anyFromFilter(alloc, v); out.flow_run_ids_not_any = try notAnyFromFilter(alloc, v); } if (obj.get("task_run_id")) |v| { out.task_run_ids_any = try anyFromFilter(alloc, v); out.task_run_ids_not_any = try notAnyFromFilter(alloc, v); } if (obj.get("type")) |v| { out.types_any = try anyFromFilter(alloc, v); out.types_not_any = try notAnyFromFilter(alloc, v); }}
fn parseCollectionFilter(alloc: std.mem.Allocator, af: json.Value, out: *db.artifacts.ArtifactCollectionFilter) !void { if (af != .object) return; const obj = af.object; if (obj.get("latest_id")) |v| { out.latest_ids_any = try anyFromFilter(alloc, v); } if (obj.get("key")) |v| { out.keys_any = try anyFromFilter(alloc, v); out.key_like = likeFromFilter(v); out.key_exists = existsFromFilter(v); } if (obj.get("flow_run_id")) |v| { out.flow_run_ids_any = try anyFromFilter(alloc, v); out.flow_run_ids_not_any = try notAnyFromFilter(alloc, v); } if (obj.get("task_run_id")) |v| { out.task_run_ids_any = try anyFromFilter(alloc, v); out.task_run_ids_not_any = try notAnyFromFilter(alloc, v); } if (obj.get("type")) |v| { out.types_any = try anyFromFilter(alloc, v); out.types_not_any = try notAnyFromFilter(alloc, v); }}
// ============================================================// Helpers// ============================================================
fn writeRaw(jw: *json.Stringify, raw: []const u8) !void { try jw.beginWriteRaw(); try jw.writer.writeAll(raw); jw.endWriteRaw();}
fn writeArtifact(alloc: std.mem.Allocator, row: db.artifacts.ArtifactRow) ![]const u8 { var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try writeArtifactObject(&jw, row); return output.toOwnedSlice();}
fn writeArtifactObject(jw: *json.Stringify, row: db.artifacts.ArtifactRow) !void { try jw.beginObject(); try jw.objectField("id"); try jw.write(row.id); try jw.objectField("created"); try jw.write(row.created); try jw.objectField("updated"); try jw.write(row.updated); try jw.objectField("key"); if (row.key) |v| try jw.write(v) else try jw.write(null); try jw.objectField("task_run_id"); if (row.task_run_id) |v| try jw.write(v) else try jw.write(null); try jw.objectField("flow_run_id"); if (row.flow_run_id) |v| try jw.write(v) else try jw.write(null); try jw.objectField("type"); if (row.type) |v| try jw.write(v) else try jw.write(null); try jw.objectField("data"); if (row.data) |raw| try writeRaw(jw, raw) else try jw.write(null); try jw.objectField("description"); if (row.description) |v| try jw.write(v) else try jw.write(null); try jw.objectField("metadata_"); if (row.metadata_) |raw| try writeRaw(jw, raw) else try jw.write(null); try jw.endObject();}
fn writeCollection(alloc: std.mem.Allocator, row: db.artifacts.ArtifactCollectionRow) ![]const u8 { var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try writeCollectionObject(&jw, row); return output.toOwnedSlice();}
fn writeCollectionObject(jw: *json.Stringify, row: db.artifacts.ArtifactCollectionRow) !void { try jw.beginObject(); try jw.objectField("id"); try jw.write(row.id); try jw.objectField("created"); try jw.write(row.created); try jw.objectField("updated"); try jw.write(row.updated); try jw.objectField("key"); try jw.write(row.key); try jw.objectField("latest_id"); try jw.write(row.latest_id); try jw.objectField("task_run_id"); if (row.task_run_id) |v| try jw.write(v) else try jw.write(null); try jw.objectField("flow_run_id"); if (row.flow_run_id) |v| try jw.write(v) else try jw.write(null); try jw.objectField("type"); if (row.type) |v| try jw.write(v) else try jw.write(null); try jw.objectField("data"); if (row.data) |raw| try writeRaw(jw, raw) else try jw.write(null); try jw.objectField("description"); if (row.description) |v| try jw.write(v) else try jw.write(null); try jw.objectField("metadata_"); if (row.metadata_) |raw| try writeRaw(jw, raw) else try jw.write(null); try jw.endObject();}
test "artifact filters propagate allocation failure without dropping constraints" { try @import("json_test.zig").checkFilterStrings(parseStringArray);}
test "supplied artifact JSON cannot become absent on allocation failure" { const Check = struct { fn encode(alloc: Allocator, value: json.Value) ![]const u8 { return (try stringifyOrNull(alloc, value)) orelse error.MissingPayload; } }; try @import("json_test.zig").checkSerialization(Check.encode);}
test "request allocation failure is not a validation response" { try @import("response_test.zig").expectRequestAllocationError(handle, "/api/artifacts/", "{\"key\": \"x\", \"data\": {\"x\": 1}}");}