const 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}}"); }