Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434const 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 VariableCreate / VariableUpdate =====
const VariableCreateBody = struct { name: []const u8, value: ?json.Value = null, tags: ?json.Value = null,};
const VariableUpdateBody = struct { name: ?[]const u8 = null, value: ?json.Value = null, tags: ?json.Value = null,};
const FilterBody = struct { limit: ?usize = null, offset: ?usize = null, variables: ?json.Value = null, sort: ?[]const u8 = 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 stringifyOrDefault(alloc: Allocator, value: ?json.Value, default_literal: []const u8) ![]const u8 { if (value) |v| return try stringifyValue(alloc, v); return default_literal;}
fn stringifyOrNull(alloc: Allocator, value: ?json.Value) !?[]const u8 { if (value) |v| return try stringifyValue(alloc, v); return null;}
fn sendValidationError(res: *wap.Response, detail: []const u8) !void { _ = res.setStatus(.unprocessable_entity); try res.writeJson(.{ .detail = detail });}
pub 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 countVariables(res); return; }
if (mem.eql(u8, method, "POST") and (mem.eql(u8, target, "/variables/") or mem.eql(u8, target, "/api/variables/"))) { try createVariable(req, res); return; }
if (mem.eql(u8, method, "GET") and mem.indexOf(u8, target, "/name/") != null) { const name = extractName(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "name required" }); return; }; try getByName(res, name); return; }
if (mem.eql(u8, method, "PATCH") and mem.indexOf(u8, target, "/name/") != null) { const name = extractName(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "name required" }); return; }; try updateByName(req, res, name); return; }
if (mem.eql(u8, method, "DELETE") and mem.indexOf(u8, target, "/name/") != null) { const name = extractName(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "name required" }); return; }; try deleteByName(res, name); return; }
if (mem.eql(u8, method, "GET")) { const id = extractId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "variable id required" }); return; }; try getById(res, id); return; }
if (mem.eql(u8, method, "PATCH")) { const id = extractId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "variable id required" }); return; }; try updateById(req, res, id); return; }
if (mem.eql(u8, method, "DELETE")) { const id = extractId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "variable id required" }); return; }; try deleteById(res, id); return; }
_ = res.setStatus(.not_implemented); try res.writeJson(.{ .detail = "not implemented" });}
fn extractId(target: []const u8) ?[]const u8 { const prefix = if (mem.startsWith(u8, target, "/api/variables/")) "/api/variables/" else "/variables/"; if (target.len > prefix.len) { return target[prefix.len..]; } return null;}
fn extractName(target: []const u8) ?[]const u8 { const idx = mem.indexOf(u8, target, "/name/") orelse return null; const start = idx + "/name/".len; if (start < target.len) { return target[start..]; } return null;}
fn createVariable(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
const body = req.parseJson(VariableCreateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; };
// check for existing — python's create_variable surfaces 409 with the // conflicting name embedded in the detail. if (try db.variables.getByName(alloc, body.name)) |_| { const detail = std.fmt.allocPrint(alloc, "Variable with name '{s}' already exists.", .{body.name}) catch "Variable already exists"; _ = res.setStatus(.conflict); try res.writeJson(.{ .detail = detail }); return; }
const value_json = try stringifyOrDefault(alloc, body.value, "null"); const tags_json = try stringifyOrDefault(alloc, body.tags, "[]");
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);
db.variables.insert(new_id, body.name, value_json, tags_json, now) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "insert failed" }); return; };
const variable = db.variables.VariableRow{ .id = new_id, .created = now, .updated = now, .name = body.name, .value = value_json, .tags = tags_json, };
const resp = writeVariable(alloc, variable) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "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.variables.getById(alloc, id)) |variable| { const resp = writeVariable(alloc, variable) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); } else { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Variable not found" }); }}
fn getByName(res: *wap.Response, name: []const u8) !void { const alloc = res.arena;
if (try db.variables.getByName(alloc, name)) |variable| { const resp = writeVariable(alloc, variable) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); } else { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Variable not found" }); }}
fn updateById(req: *wap.Request, res: *wap.Response, id: []const u8) !void { const alloc = req.arena;
const body = req.parseJson(VariableUpdateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; };
const value_json = try stringifyOrNull(alloc, body.value); const tags_json = try stringifyOrNull(alloc, body.tags);
var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf);
const did_update = db.variables.updateById(id, body.name, value_json, tags_json, now) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "update failed" }); return; };
if (!did_update) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Variable not found" }); return; }
try res.sendEmpty(.no_content);}
fn updateByName(req: *wap.Request, res: *wap.Response, name: []const u8) !void { const alloc = req.arena;
const body = req.parseJson(VariableUpdateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; };
const value_json = try stringifyOrNull(alloc, body.value); const tags_json = try stringifyOrNull(alloc, body.tags);
var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf);
const did_update = db.variables.updateByName(name, body.name, value_json, tags_json, now) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "update failed" }); return; };
if (!did_update) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Variable not found" }); return; }
try res.sendEmpty(.no_content);}
fn deleteById(res: *wap.Response, id: []const u8) !void { const deleted = db.variables.deleteById(id) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "delete failed" }); return; };
if (!deleted) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Variable not found" }); return; }
try res.sendEmpty(.no_content);}
fn deleteByName(res: *wap.Response, name: []const u8) !void { const deleted = db.variables.deleteByName(name) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "delete failed" }); return; };
if (!deleted) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Variable not found" }); return; }
try res.sendEmpty(.no_content);}
fn filter(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
var limit: usize = 200; var offset: usize = 0;
if (req.body.len > 0) { if (req.parseJson(FilterBody)) |body| { if (body.limit) |l| limit = l; if (body.offset) |o| offset = o; } else |parse_err| { if (parse_err == error.OutOfMemory) return parse_err; } }
const variables = db.variables.list(alloc, limit, offset) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "database error" }); return; };
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 (variables) |variable| { try writeVariableObject(&jw, variable); }
try jw.endArray();
_ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice());}
fn countVariables(res: *wap.Response) !void { const cnt = try db.variables.count(); try res.writeJson(cnt);}
fn writeVariable(alloc: std.mem.Allocator, variable: db.variables.VariableRow) ![]const u8 { var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try writeVariableObject(&jw, variable); return output.toOwnedSlice();}
fn writeVariableObject(jw: *json.Stringify, variable: db.variables.VariableRow) !void { try jw.beginObject();
try jw.objectField("id"); try jw.write(variable.id);
try jw.objectField("created"); try jw.write(variable.created);
try jw.objectField("updated"); try jw.write(variable.updated);
try jw.objectField("name"); try jw.write(variable.name);
try jw.objectField("value"); try jw.beginWriteRaw(); try jw.writer.writeAll(variable.value); jw.endWriteRaw();
try jw.objectField("tags"); try jw.beginWriteRaw(); try jw.writer.writeAll(variable.tags); jw.endWriteRaw();
try jw.endObject();}
test "supplied JSON allocation failure cannot substitute a default payload" { const Check = struct { fn encode(alloc: Allocator, value: json.Value) ![]const u8 { return stringifyOrDefault(alloc, value, "null"); } }; try @import("json_test.zig").checkSerialization(Check.encode); var failing = std.testing.FailingAllocator.init(std.testing.allocator, .{ .fail_index = 0 }); try std.testing.expectEqualStrings("null", try stringifyOrDefault(failing.allocator(), null, "null"));}
test "request allocation failure is not a validation response" { try @import("response_test.zig").expectRequestAllocationError(handle, "/api/variables/", "{\"name\": \"x\", \"value\": {\"x\": 1}}");}