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"); const bulk_filter = @import("bulk_filter.zig"); // ===== typed bodies — mirror python's FlowCreate / FlowUpdate ===== const FlowCreateBody = struct { name: []const u8, tags: ?json.Value = null, labels: ?json.Value = null, }; const FlowUpdateBody = struct { tags: ?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 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); } // POST /flows/ - create or get flow by name // POST /flows/filter - list flows // GET /flows/name/{name} - get flow by name // GET /flows/{id} - get flow by id // PATCH /flows/{id} - update flow // DELETE /flows/{id} - delete flow 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 countFlows(res); return; } if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/paginate")) { try paginateFlows(req, res); return; } if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/bulk_delete")) { try bulkDeleteFlows(req, res); return; } const prefix = if (mem.startsWith(u8, target, "/api/flows/")) "/api/flows/" else "/flows/"; // GET /flows/name/{name} — must run before generic /flows/{id} if (mem.eql(u8, method, "GET") and target.len > prefix.len + "name/".len and mem.startsWith(u8, target[prefix.len..], "name/")) { const flow_name = target[prefix.len + "name/".len ..]; try getFlowByName(res, flow_name); return; } const has_id = target.len > prefix.len; const flow_id = if (has_id) target[prefix.len..] else ""; if (mem.eql(u8, method, "POST") and (mem.eql(u8, target, "/flows/") or mem.eql(u8, target, "/api/flows/"))) { try createFlow(req, res); } else if (mem.eql(u8, method, "GET") and has_id) { try getFlow(res, flow_id); } else if (mem.eql(u8, method, "PATCH") and has_id) { try patchFlow(req, res, flow_id); } else if (mem.eql(u8, method, "DELETE") and has_id) { try deleteFlow(res, flow_id); } else if (mem.eql(u8, method, "GET") or mem.eql(u8, method, "PATCH") or mem.eql(u8, method, "DELETE")) { try sendError(res, .bad_request, "flow id required"); } else { try sendError(res, .not_implemented, "not implemented"); } } fn createFlow(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena; const body = req.parseJson(FlowCreateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; // try to get existing flow first (idempotent) if (try db.getFlowByName(alloc, body.name)) |flow| { const resp = writeFlow(alloc, flow) catch { try sendError(res, .internal_server_error, "serialize error"); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); return; } var new_id_buf: [36]u8 = undefined; const new_id = uuid_util.generate(runtime.appIo(), &new_id_buf); db.insertFlow(new_id, body.name) catch { try sendError(res, .internal_server_error, "insert failed"); return; }; var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); const flow = db.FlowRow{ .id = new_id, .created = now, .updated = now, .name = body.name, .tags = "[]", }; const resp = writeFlow(alloc, flow) catch { try sendError(res, .internal_server_error, "serialize error"); return; }; _ = res.setStatus(.created); _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); } fn getFlow(res: *wap.Response, flow_id: []const u8) !void { const alloc = res.arena; if (try db.getFlowById(alloc, flow_id)) |flow| { const resp = writeFlow(alloc, flow) 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, "flow not found"); } } fn getFlowByName(res: *wap.Response, flow_name: []const u8) !void { const alloc = res.arena; if (try db.getFlowByName(alloc, flow_name)) |flow| { const resp = writeFlow(alloc, flow) 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, "flow not found"); } } fn patchFlow(req: *wap.Request, res: *wap.Response, flow_id: []const u8) !void { const alloc = req.arena; const body = req.parseJson(FlowUpdateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; const tags_json: ?[]const u8 = if (body.tags) |v| try stringifyValue(alloc, v) else null; const updated = try db.updateFlow(flow_id, tags_json); if (!updated) { try sendError(res, .not_found, "flow not found"); return; } try res.sendEmpty(.no_content); } fn deleteFlow(res: *wap.Response, flow_id: []const u8) !void { const deleted = db.deleteFlow(flow_id) catch { try sendError(res, .internal_server_error, "database error"); return; }; if (!deleted) { try sendError(res, .not_found, "flow not found"); return; } try res.sendEmpty(.no_content); } /// `POST /flows/count` — mirrors python `count_flows`. Body is the unified /// filter envelope (`flows`, `flow_runs`, `task_runs`, `deployments`, /// `work_pools`). We accept the envelope shape but don't filter (matching /// the depth of our existing /filter implementation); returns total count. fn countFlows(res: *wap.Response) !void { const n = db.flows.count() catch { _ = res.setHeader("retry-after", "1"); try sendError(res, .service_unavailable, "database unavailable"); return; }; try res.writeJson(n); } /// Body for POST /flows/paginate. The filter envelope fields are accepted /// but unused for now — same depth as existing /filter. `limit` defaults to /// 50 (matching python's LimitBody for flows); `page` is 1-indexed. 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 /flows/paginate` — mirrors python `paginate_flows`. Returns /// `{results, count, limit, pages, page}`. fn paginateFlows(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; const offset: i64 = (page - 1) * limit; const flows = db.flows.listWithOffset(alloc, @intCast(limit), @intCast(@max(offset, 0))) catch { try sendError(res, .internal_server_error, "database error"); return; }; const total = db.flows.count() catch { _ = res.setHeader("retry-after", "1"); try sendError(res, .service_unavailable, "database unavailable"); return; }; 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 (flows) |flow| try writeFlowObject(&jw, flow); 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()); } const BULK_OPERATION_LIMIT: i64 = 50; const BulkDeleteBody = struct { flows: ?json.Value = null, flow_runs: ?json.Value = null, task_runs: ?json.Value = null, deployments: ?json.Value = null, work_pools: ?json.Value = null, limit: ?i64 = null, }; /// `POST /flows/bulk_delete` — deletes the flows in `flows.id.any_`, or with /// no filter at all the newest `limit` flows (python's unfiltered semantics). /// Any other predicate is refused (422) rather than ignored: an ignored /// filter here deletes flows the caller excluded, and their deployments with /// them. Returns `{deleted: [UUID]}` matching python's FlowBulkDeleteResponse. fn bulkDeleteFlows(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena; var limit: i64 = BULK_OPERATION_LIMIT; var selected: ?[]const []const u8 = null; if (req.body.len > 0) { if (req.parseJson(BulkDeleteBody)) |body| { if (body.limit) |l| limit = l; } else |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; } const parsed = json.parseFromSlice(json.Value, alloc, req.body, .{}) catch { return sendValidationError(res, "invalid json"); }; if (parsed.value != .object) return sendValidationError(res, "request body must be an object"); var buf: [256]u8 = undefined; if (bulk_filter.firstUnhonored(parsed.value.object, &.{"flows.id.any_"}, &buf)) |path| { return sendValidationError(res, try std.fmt.allocPrint(alloc, "bulk_delete cannot apply the filter {s}; nothing was deleted", .{path})); } selected = bulk_filter.idAny(alloc, parsed.value.object, "flows") catch { return sendValidationError(res, "flows.id.any_ must be a list of ids"); }; } if (limit < 1) limit = 1; if (limit > BULK_OPERATION_LIMIT) limit = BULK_OPERATION_LIMIT; const ids: []const []const u8 = selected orelse blk: { const flows = db.flows.list(alloc, @intCast(limit)) catch { try sendError(res, .internal_server_error, "database error"); return; }; const out = try alloc.alloc([]const u8, flows.len); for (flows, 0..) |flow, i| out[i] = flow.id; break :blk out; }; var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try jw.beginObject(); try jw.objectField("deleted"); try jw.beginArray(); for (ids[0..@min(ids.len, @as(usize, @intCast(limit)))]) |id| { const did_delete = db.flows.delete(id) catch false; if (did_delete) try jw.write(id); } try jw.endArray(); 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; const Body = struct { limit: ?usize = null, offset: usize = 0, 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, sort: ?[]const u8 = null, }; const body = if (req.body.len == 0) Body{} else req.parseJson(Body) catch |parse_err| { if (parse_err == error.OutOfMemory) return parse_err; return sendValidationError(res, "invalid flow filter"); }; var name_like: ?[]const u8 = null; if (body.flows) |f| { if (f != .object and f != .null) return sendValidationError(res, "flows must be an object"); if (f == .object) { if (f.object.get("name")) |name| { if (name != .object and name != .null) return sendValidationError(res, "name must be an object"); if (name == .object) { if (name.object.get("like_")) |like| { if (like != .string and like != .null) return sendValidationError(res, "name.like_ must be a string"); if (like == .string) name_like = like.string; } } } } } const flows = db.flows.listByName(alloc, body.limit orelse 200, body.offset, name_like) 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 }; jw.beginArray() catch { try sendError(res, .internal_server_error, "serialize error"); return; }; for (flows) |flow| { try writeFlowObject(&jw, flow); } try jw.endArray(); _ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice()); } fn writeFlow(alloc: std.mem.Allocator, flow: db.FlowRow) ![]const u8 { var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try writeFlowObject(&jw, flow); return output.toOwnedSlice(); } fn writeFlowObject(jw: *json.Stringify, flow: db.FlowRow) !void { try jw.beginObject(); try jw.objectField("id"); try jw.write(flow.id); try jw.objectField("created"); try jw.write(flow.created); try jw.objectField("updated"); try jw.write(flow.updated); try jw.objectField("name"); try jw.write(flow.name); try jw.objectField("tags"); try jw.beginWriteRaw(); try jw.writer.writeAll(flow.tags); jw.endWriteRaw(); try jw.endObject(); } test "JSON serialization releases partial output on allocation failure" { try @import("json_test.zig").checkSerialization(stringifyValue); } test "request allocation failure is not a validation response" { try @import("response_test.zig").expectRequestAllocationError(handle, "/api/flows/", "{\"name\": \"x\"}"); }