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"); const schedules = @import("deployment_schedules.zig"); const param_schema = @import("../utilities/parameter_schema.zig"); const hydration = @import("../utilities/hydration.zig"); // ===== typed request bodies — mirror python's DeploymentCreate etc. ===== // wap.parseJson is strict (matches pydantic ActionBaseModel `extra="forbid"`) // — every field python's schema declares must appear here. JSON-blob fields // stored as TEXT in the DB are typed as `?json.Value` so std.json parses // them once; we stringify on demand for storage and re-emit raw for output. const DeploymentCreateBody = struct { name: []const u8, flow_id: []const u8, paused: bool = false, schedules: ?json.Value = null, concurrency_limit: ?i64 = null, concurrency_options: ?json.Value = null, global_concurrency_limit_id: ?[]const u8 = null, enforce_parameter_schema: bool = true, parameter_openapi_schema: ?json.Value = null, parameters: ?json.Value = null, tags: ?json.Value = null, labels: ?json.Value = null, pull_steps: ?json.Value = null, work_queue_name: ?[]const u8 = null, work_pool_name: ?[]const u8 = null, storage_document_id: ?[]const u8 = null, infrastructure_document_id: ?[]const u8 = null, description: ?[]const u8 = null, path: ?[]const u8 = null, version: ?[]const u8 = null, entrypoint: ?[]const u8 = null, job_variables: ?json.Value = null, version_info: ?json.Value = null, }; const DeploymentUpdateBody = struct { version: ?[]const u8 = null, description: ?[]const u8 = null, paused: ?bool = null, schedules: ?json.Value = null, concurrency_limit: ?i64 = null, concurrency_options: ?json.Value = null, global_concurrency_limit_id: ?[]const u8 = null, enforce_parameter_schema: ?bool = null, parameters: ?json.Value = null, parameter_openapi_schema: ?json.Value = null, tags: ?json.Value = null, labels: ?json.Value = null, pull_steps: ?json.Value = null, work_queue_name: ?[]const u8 = null, work_pool_name: ?[]const u8 = null, storage_document_id: ?[]const u8 = null, infrastructure_document_id: ?[]const u8 = null, path: ?[]const u8 = null, entrypoint: ?[]const u8 = null, job_variables: ?json.Value = null, version_info: ?json.Value = null, }; const CreateFlowRunStateBody = struct { type: []const u8, name: ?[]const u8 = null, message: ?[]const u8 = null, data: ?json.Value = null, state_details: ?json.Value = null, }; const CreateFlowRunFromDeploymentBody = struct { name: ?[]const u8 = null, state: ?CreateFlowRunStateBody = null, parameters: ?json.Value = null, context: ?json.Value = null, parent_task_run_id: ?[]const u8 = null, infrastructure_document_id: ?[]const u8 = null, empirical_policy: ?json.Value = null, tags: ?json.Value = null, labels: ?json.Value = null, idempotency_key: ?[]const u8 = null, work_queue_name: ?[]const u8 = null, job_variables: ?json.Value = null, enforce_parameter_schema: ?bool = null, }; const GetScheduledFlowRunsBody = struct { deployment_ids: ?[]const []const u8 = null, scheduled_before: ?[]const u8 = null, scheduled_after: ?[]const u8 = null, limit: ?usize = null, }; const DeploymentFilterBody = struct { limit: ?usize = null, offset: ?usize = null, // freeform filter sub-objects (deployments.id.any_, etc.) — accepted // but unused today. Declared so strict-mode doesn't 422 the python client. deployments: ?json.Value = null, flows: ?json.Value = null, flow_runs: ?json.Value = null, task_runs: ?json.Value = null, work_pools: ?json.Value = null, work_pool_queues: ?json.Value = null, sort: ?[]const u8 = null, }; /// Stringify a json.Value into bytes owned by `alloc`. Used to convert /// parsed-object fields into the blob shape the deployments table accepts. 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(); } /// Stringify with a fallback default when the field isn't present. The /// pydantic schema's `default_factory=dict` / `default_factory=list` semantics /// are expressed here by passing `default_literal = "{}"` or `"[]"`. 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 stringifyNullableValue(alloc: Allocator, value: json.Value) !?[]const u8 { if (value == .null) return null; return try stringifyValue(alloc, value); } fn requestFieldValue(alloc: Allocator, body: []const u8, field: []const u8) !?json.Value { const parsed = json.parseFromSlice(json.Value, alloc, body, .{}) catch |err| switch (err) { error.OutOfMemory => return err, else => return null, }; if (parsed.value != .object) return null; return parsed.value.object.get(field); } fn requestHasField(alloc: Allocator, body: []const u8, field: []const u8) !bool { return try requestFieldValue(alloc, body, field) != 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); // POST /deployments/filter if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/filter")) { try filter(req, res); return; } // POST /deployments/count if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/count")) { try count(res); return; } // POST /deployments/paginate if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/paginate")) { try paginate(req, res); return; } // POST /deployments/bulk_delete if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/bulk_delete")) { try bulkDelete(req, res); return; } // POST /deployments/get_scheduled_flow_runs if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/get_scheduled_flow_runs")) { try getScheduledFlowRuns(req, res); return; } // GET /deployments/name/{flow_name}/{deployment_name} if (mem.eql(u8, method, "GET") and mem.indexOf(u8, target, "/name/") != null) { try getByName(res, target); return; } // POST /deployments/{id}/create_flow_run if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/create_flow_run")) { try createFlowRun(req, res, target); return; } // POST /deployments/{id}/pause_deployment if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/pause_deployment")) { try pause(res, target); return; } // POST /deployments/{id}/resume_deployment if (mem.eql(u8, method, "POST") and mem.endsWith(u8, target, "/resume_deployment")) { try resume_(res, target); return; } // Schedule endpoints if (mem.indexOf(u8, target, "/schedules") != null) { try schedules.handle(req, res, target); return; } // POST /deployments/ - create deployment if (mem.eql(u8, method, "POST")) { const is_root = mem.endsWith(u8, target, "/deployments/") or mem.endsWith(u8, target, "/deployments"); if (is_root) { try create(req, res); return; } } // GET /deployments/{id} if (mem.eql(u8, method, "GET")) { const id = extractDeploymentId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "deployment id required" }); return; }; try read(res, id); return; } // PATCH /deployments/{id} if (mem.eql(u8, method, "PATCH")) { const id = extractDeploymentId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "deployment id required" }); return; }; try update(req, res, id); return; } // DELETE /deployments/{id} if (mem.eql(u8, method, "DELETE")) { const id = extractDeploymentId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "deployment id required" }); return; }; try delete(res, id); return; } _ = res.setStatus(.not_implemented); try res.writeJson(.{ .detail = "not implemented" }); } // Path helper pub fn extractDeploymentId(target: []const u8) ?[]const u8 { const prefix = if (mem.startsWith(u8, target, "/api/deployments/")) "/api/deployments/" else if (mem.startsWith(u8, target, "/deployments/")) "/deployments/" else return null; if (target.len <= prefix.len) return null; const after = target[prefix.len..]; const end = mem.indexOf(u8, after, "/") orelse after.len; if (end == 0) return null; return after[0..end]; } // CRUD handlers fn create(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena; const body = req.parseJson(DeploymentCreateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; const raw_schedules = try requestFieldValue(alloc, req.body, "schedules"); const raw_concurrency_options = try requestFieldValue(alloc, req.body, "concurrency_options"); const has_concurrency_limit = try requestHasField(alloc, req.body, "concurrency_limit"); // Verify flow exists _ = try db.flows.getById(alloc, body.flow_id) orelse { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Flow not found" }); return; }; var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); // Check for existing deployment (upsert by flow_id + name) if (try db.deployments.getByFlowAndName(alloc, body.flow_id, body.name)) |existing| { var params = try buildUpdateParamsFromCreate(alloc, body); try resolveUpdateQueue(alloc, ¶ms, now); _ = db.deployments.updateById(existing.id, now, params) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "update failed" }); return; }; // POST /deployments/ is an upsert. Prefect's deploy path includes // concurrency_limit=null and schedules=null when the local deployment // no longer configures them, so explicit null must clear stale rows. if (has_concurrency_limit) { try applyConcurrencyLimit(alloc, existing.id, body.concurrency_limit); } if (raw_concurrency_options) |options_val| { try applyConcurrencyOptions(alloc, existing.id, options_val, now); } if (raw_schedules) |sched_val| { try schedules.replaceSchedules(alloc, existing.id, sched_val, now); } schedules.clearScheduledRuns(alloc, existing.id, .auto_scheduled_future, now); const deployment = try db.deployments.getById(alloc, existing.id) orelse { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "not found after update" }); return; }; const resp = writeDeployment(alloc, deployment) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); return; } // Create new var id_buf: [36]u8 = undefined; const new_id = uuid_util.generate(runtime.appIo(), &id_buf); var insert_params = try buildInsertParamsFromCreate(alloc, body); if (raw_concurrency_options) |options_val| { insert_params.concurrency_options = try stringifyNullableValue(alloc, options_val); } // Resolve work_queue_id from work_pool_name if provided if (insert_params.work_pool_name) |pool_name| { if (try db.work_pools.getByName(alloc, pool_name)) |pool| { if (insert_params.work_queue_name) |queue_name| { if (try db.work_queues.getByPoolAndName(alloc, pool.id, queue_name)) |queue| { insert_params.work_queue_id = queue.id; } } else if (pool.default_queue_id) |default_id| { insert_params.work_queue_id = default_id; insert_params.work_queue_name = "default"; } } } db.deployments.insert(new_id, body.name, body.flow_id, now, insert_params) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "insert failed" }); return; }; // Apply `concurrency_limit: N` -> auto-managed v2 limit, set FK if (has_concurrency_limit) { try applyConcurrencyLimit(alloc, new_id, body.concurrency_limit); } if (raw_schedules) |sched_val| { try schedules.replaceSchedules(alloc, new_id, sched_val, now); } const deployment = try db.deployments.getById(alloc, new_id) orelse { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "not found after insert" }); return; }; const resp = writeDeployment(alloc, deployment) 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 read(res: *wap.Response, id: []const u8) !void { const alloc = res.arena; const deployment = try db.deployments.getById(alloc, id) orelse { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Deployment not found" }); return; }; const resp = writeDeployment(alloc, deployment) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); } fn getByName(res: *wap.Response, target: []const u8) !void { const alloc = res.arena; const name_idx = mem.indexOf(u8, target, "/name/") orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "invalid path" }); return; }; const after_name = target[name_idx + 6 ..]; const sep_idx = mem.indexOf(u8, after_name, "/") orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "deployment name required" }); return; }; const flow_name = after_name[0..sep_idx]; const deployment_name = after_name[sep_idx + 1 ..]; if (deployment_name.len == 0) { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "deployment name required" }); return; } const flow = try db.flows.getByName(alloc, flow_name) orelse { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Flow not found" }); return; }; const deployment = try db.deployments.getByFlowAndName(alloc, flow.id, deployment_name) orelse { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Deployment not found" }); return; }; const resp = writeDeployment(alloc, deployment) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; }; _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); } fn update(req: *wap.Request, res: *wap.Response, id: []const u8) !void { const alloc = req.arena; const body = req.parseJson(DeploymentUpdateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; const raw_schedules = try requestFieldValue(alloc, req.body, "schedules"); const raw_concurrency_options = try requestFieldValue(alloc, req.body, "concurrency_options"); const has_concurrency_limit = try requestHasField(alloc, req.body, "concurrency_limit"); var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); var params = try buildUpdateParamsFromUpdate(alloc, body); try resolveUpdateQueue(alloc, ¶ms, now); const updated = db.deployments.updateById(id, now, params) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "update failed" }); return; }; if (!updated) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Deployment not found" }); return; } if (has_concurrency_limit) { try applyConcurrencyLimit(alloc, id, body.concurrency_limit); } if (raw_concurrency_options) |options_val| { try applyConcurrencyOptions(alloc, id, options_val, now); } if (raw_schedules) |sched_val| { try schedules.replaceSchedules(alloc, id, sched_val, now); } schedules.clearScheduledRuns(alloc, id, .auto_scheduled_future, now); try res.sendEmpty(.no_content); } fn delete(res: *wap.Response, id: []const u8) !void { schedules.clearScheduledRuns(res.arena, id, .all, null); const deleted = db.deployments.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 = "Deployment 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; var name_like: ?[]const u8 = null; var names: ?[]const []const u8 = null; var ids: ?[]const []const u8 = null; // Empty body is valid (list-all). Non-empty: parse strict-but-tolerant — // unknown filter sub-objects are declared in DeploymentFilterBody but // unused, so the python client's full filter blob still parses. if (req.body.len > 0) { if (req.parseJson(DeploymentFilterBody)) |body| { if (body.limit) |l| limit = l; if (body.offset) |o| offset = o; if (body.deployments) |f| { if (f != .object and f != .null) return sendValidationError(res, "deployments 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 parsed_root = json.parseFromSlice(json.Value, alloc, req.body, .{}) catch { return sendValidationError(res, "invalid deployment filter"); }; if (parsed_root.value == .object) { names = anyStrings(alloc, parsed_root.value.object, "name") catch { return sendValidationError(res, "name.any_ must be a list of strings"); }; ids = bulk_filter.idAny(alloc, parsed_root.value.object, "deployments") catch { return sendValidationError(res, "id.any_ must be a list of ids"); }; } } } } else |_| { return sendValidationError(res, "invalid deployment filter"); } } // name.any_ / id.any_ are exact-match sets, as in python. Deployment names // are arbitrary text, so rather than inline them into SQL the matching rows // are selected from the full list (a few dozen) and paged afterwards. const exact = names != null or ids != null; const fetched = db.deployments.listByName( alloc, if (exact) std.math.maxInt(i32) else limit, if (exact) 0 else offset, name_like, ) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "database error" }); return; }; const deployments_list = if (!exact) fetched else blk: { var kept: std.ArrayListUnmanaged(db.deployments.DeploymentRow) = .empty; for (fetched) |d| { if (names) |ns| if (!containsString(ns, d.name)) continue; if (ids) |is| if (!containsString(is, d.id)) continue; try kept.append(alloc, d); } const start = @min(offset, kept.items.len); break :blk kept.items[start..@min(kept.items.len, start + limit)]; }; 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 (deployments_list) |d| { try writeDeploymentObject(&jw, d, alloc); } try jw.endArray(); _ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice()); } /// `deployments..any_` as a list, or null when absent. A present empty /// list is returned as such: python's `col.in_([])` matches nothing. fn anyStrings(alloc: Allocator, root: json.ObjectMap, field: []const u8) !?[]const []const u8 { const section = root.get("deployments") orelse return null; if (section != .object) return null; const f = section.object.get(field) orelse return null; if (f != .object) return null; const any = f.object.get("any_") orelse return null; if (any == .null) return null; if (any != .array) return error.InvalidFilter; const out = try alloc.alloc([]const u8, any.array.items.len); for (any.array.items, 0..) |item, i| { if (item != .string) return error.InvalidFilter; out[i] = item.string; } return out; } fn containsString(list: []const []const u8, item: []const u8) bool { for (list) |x| if (mem.eql(u8, x, item)) return true; return false; } fn count(res: *wap.Response) !void { const c = try db.deployments.count(); // Count endpoints return bare integers as application/json bodies — // writeJson handles i64 natively. try res.writeJson(c); } const BULK_OPERATION_LIMIT: i64 = 200; 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, work_pool_queues: ?json.Value = null, sort: ?[]const u8 = null, }; /// `POST /deployments/paginate` — `{results, count, limit, pages, page}`, /// matching python's `DeploymentPaginationResponse`. fn paginate(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 deployments_list = db.deployments.list(alloc, @intCast(limit), @intCast(@max(offset, 0))) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "database error" }); return; }; const total = try db.deployments.count(); const pages = if (limit > 0) @divFloor(@as(i64, @intCast(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 (deployments_list) |d| try writeDeploymentObject(&jw, d, alloc); try jw.endArray(); try jw.objectField("count"); try jw.write(@as(i64, @intCast(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 BulkDeleteBody = struct { deployments: ?json.Value = null, limit: ?i64 = null, }; /// `POST /deployments/bulk_delete` — deletes the deployments in /// `deployments.id.any_`, or with no filter at all the first `limit` /// deployments (python's unfiltered semantics). Any other predicate is /// refused (422) rather than ignored, since ignoring it deletes deployments /// the caller excluded. Returns `{deleted: [UUID]}` matching python's /// DeploymentBulkDeleteResponse. fn bulkDelete(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, &.{"deployments.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, "deployments") catch { return sendValidationError(res, "deployments.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 deployments_list = db.deployments.list(alloc, @intCast(limit), 0) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "database error" }); return; }; const out = try alloc.alloc([]const u8, deployments_list.len); for (deployments_list, 0..) |d, i| out[i] = d.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| { schedules.clearScheduledRuns(alloc, id, .all, null); const did_delete = db.deployments.deleteById(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()); } // Action handlers fn createFlowRun(req: *wap.Request, res: *wap.Response, target: []const u8) !void { const alloc = req.arena; const id = extractDeploymentId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "deployment id required" }); return; }; const deployment = try db.deployments.getById(alloc, id) orelse { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Deployment not found" }); return; }; var state_type: []const u8 = "SCHEDULED"; var state_name: []const u8 = "Scheduled"; var state_body: ?CreateFlowRunStateBody = null; var override_parameters: ?json.Value = null; var override_job_variables: ?json.Value = null; var enforce_override: ?bool = null; var idempotency_key: ?[]const u8 = null; // body is optional — the python endpoint accepts an empty body. When // present we strict-parse against CreateFlowRunFromDeploymentBody. if (req.body.len > 0) { const body = req.parseJson(CreateFlowRunFromDeploymentBody) 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.state) |s| { state_body = s; state_type = s.type; if (s.name) |n| state_name = n; } if (body.parameters) |p| { if (p == .object) override_parameters = p; } if (body.job_variables) |jv| { if (jv == .object) override_job_variables = jv; } enforce_override = body.enforce_parameter_schema; idempotency_key = body.idempotency_key; } // Merge deployment.parameters (base) with the per-run override (shallow, // override-wins per key). Matches python prefect's behavior. const merged_parameters = try mergeParameters(alloc, deployment.parameters, override_parameters); // hydrate __prefect_kind blobs (UI-dehydrated values) before validating; // python raises HydrationError -> 400 here const run_parameters = switch (try hydration.hydrateParameters(alloc, merged_parameters)) { .ok => |hydrated| hydrated, .err => |msg| { _ = res.setStatus(.bad_request); const detail = try std.fmt.allocPrint(alloc, "Error hydrating flow run parameters: {s}", .{msg}); try res.writeJson(.{ .detail = detail }); return; }, }; // parity with python create_flow_run_from_deployment: schema enforcement // (deployment default, per-run overridable) rejects at creation time // rather than deferring the failure to the worker if (enforce_override orelse deployment.enforce_parameter_schema) { const no_schema_detail = "Error updating deployment: Cannot update parameters because parameter schema enforcement is enabled and the deployment does not have a valid parameter schema."; const schema_json = deployment.parameter_openapi_schema orelse { _ = res.setStatus(.conflict); try res.writeJson(.{ .detail = no_schema_detail }); return; }; switch (try param_schema.validateParameters(alloc, schema_json, run_parameters)) { .valid => {}, .invalid => |msg| { _ = res.setStatus(.conflict); const detail = try std.fmt.allocPrint(alloc, "Error creating flow run: {s}", .{msg}); try res.writeJson(.{ .detail = detail }); return; }, .circular_ref => { _ = res.setStatus(.unprocessable_entity); try res.writeJson(.{ .detail = "Invalid schema: Unable to validate schema with circular references." }); return; }, .invalid_schema => { _ = res.setStatus(.conflict); try res.writeJson(.{ .detail = no_schema_detail }); return; }, } } const run_job_variables_json: ?[]const u8 = if (override_job_variables) |jv| try stringifyValue(alloc, jv) else null; var id_buf: [36]u8 = undefined; const run_id = uuid_util.generate(runtime.appIo(), &id_buf); var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); const scheduled_time = scheduledTimeFromCreateState(state_type, state_body, now); const expected_start_time: ?[]const u8 = scheduled_time; const state_details_json = try buildCreateStateDetails(alloc, state_body, scheduled_time); var state_id_buf: [36]u8 = undefined; const state_id = uuid_util.generate(runtime.appIo(), &state_id_buf); var name_buf: [64]u8 = undefined; const run_name = std.fmt.bufPrint(&name_buf, "{s}-{s}", .{ deployment.name[0..@min(deployment.name.len, 20)], run_id[0..8], }) catch "run"; const insert_params: db.flow_runs.InsertParams = .{ .idempotency_key = idempotency_key, .deployment_id = deployment.id, .deployment_version = deployment.version, .work_queue_name = deployment.work_queue_name, .work_queue_id = deployment.work_queue_id, .expected_start_time = expected_start_time, .parameters = run_parameters, .state_id = state_id, .state_details = state_details_json, .job_variables = run_job_variables_json, }; if (idempotency_key != null) { _ = db.flow_runs.insertOrIgnore(run_id, deployment.flow_id, run_name, state_type, state_name, now, insert_params) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "insert failed" }); return; }; } else { db.flow_runs.insert(run_id, deployment.flow_id, run_name, state_type, state_name, now, insert_params) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "insert failed" }); return; }; } const saved_run = if (idempotency_key) |key| db.flow_runs.getByIdempotencyKey(alloc, deployment.flow_id, key) else db.flow_runs.get(alloc, run_id); const run = try saved_run orelse { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "not found after insert" }); return; }; // Python treats an empty key as an ordinary insert: the first succeeds, // then the database uniqueness constraint makes a retry a conflict. if (idempotency_key) |key| { if (key.len == 0 and !mem.eql(u8, run.id, run_id)) { _ = res.setStatus(.conflict); try res.writeJson(.{ .detail = "Data integrity conflict" }); return; } } const resp = writeFlowRunResponse(alloc, run, run.state_id orelse state_id) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "serialize error" }); return; }; _ = res.setStatus(if (mem.eql(u8, run.id, run_id)) .created else .ok); _ = res.setHeader("content-type", "application/json"); try res.sendBody(resp); } fn stateTypeIsScheduled(state_type: []const u8) bool { return mem.eql(u8, state_type, "SCHEDULED") or mem.eql(u8, state_type, "Scheduled"); } fn scheduledTimeFromCreateState(state_type: []const u8, state_body: ?CreateFlowRunStateBody, fallback: []const u8) ?[]const u8 { if (!stateTypeIsScheduled(state_type)) return null; const body = state_body orelse return fallback; const details = body.state_details orelse return fallback; if (details != .object) return fallback; const scheduled_time = details.object.get("scheduled_time") orelse return fallback; if (scheduled_time != .string or scheduled_time.string.len == 0) return fallback; return scheduled_time.string; } fn buildCreateStateDetails(alloc: Allocator, state_body: ?CreateFlowRunStateBody, scheduled_time: ?[]const u8) ![]const u8 { if (state_body) |body| { if (body.state_details) |details| { if (details == .object) return try stringifyValue(alloc, details); } } if (scheduled_time) |ts| { var out: std.Io.Writer.Allocating = .init(alloc); errdefer out.deinit(); var jw: json.Stringify = .{ .writer = &out.writer }; try jw.beginObject(); try jw.objectField("scheduled_time"); try jw.write(ts); try jw.endObject(); return out.toOwnedSlice(); } return try alloc.dupe(u8, "{}"); } fn pause(res: *wap.Response, target: []const u8) !void { const id = extractDeploymentId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "deployment id required" }); return; }; var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); const updated = db.deployments.updateById(id, now, .{ .paused = true }) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "update failed" }); return; }; if (!updated) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Deployment not found" }); return; } schedules.clearScheduledRuns(res.arena, id, .auto_scheduled, null); try res.sendEmpty(.no_content); } fn resume_(res: *wap.Response, target: []const u8) !void { const id = extractDeploymentId(target) orelse { _ = res.setStatus(.bad_request); try res.writeJson(.{ .detail = "deployment id required" }); return; }; var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); const updated = db.deployments.updateById(id, now, .{ .paused = false }) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "update failed" }); return; }; if (!updated) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Deployment not found" }); return; } try res.sendEmpty(.no_content); } fn getScheduledFlowRuns(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena; // empty body → return [] if (req.body.len == 0) { _ = res.setHeader("content-type", "application/json"); try res.sendBody("[]"); return; } const body = req.parseJson(GetScheduledFlowRunsBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; const deployment_ids = body.deployment_ids orelse { try res.writeJson(&[_]u0{}); return; }; if (deployment_ids.len == 0) { _ = res.setHeader("content-type", "application/json"); try res.sendBody("[]"); return; } const scheduled_before: ?[]const u8 = if (body.scheduled_before) |s| try normalizeTimestamp(alloc, s) else null; const limit: usize = body.limit orelse 100; const runs = db.flow_runs.getScheduledByDeployments(alloc, deployment_ids, scheduled_before, limit) 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 (runs) |run| { var state_id_buf: [36]u8 = undefined; const state_id = uuid_util.generate(runtime.appIo(), &state_id_buf); try writeFlowRunObject(&jw, run, state_id); } try jw.endArray(); _ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice()); } // Timestamp normalization - convert various timestamp formats to ISO8601 // Client may send "2026-01-22 16:40:23.915842+00:00" but db stores "2026-01-22T16:40:23.915842Z" /// Shallow merge of two parameter JSON objects, override-wins per key. /// `base_json` is the deployment-stored parameters string (always a JSON /// object literal; defaults to "{}" if the deployment was created without /// any). `override` is the parsed JSON object from the request body, or null /// if the create-from-deployment request didn't include `parameters`. /// Returns the serialized merged object. fn mergeParameters(alloc: std.mem.Allocator, base_json: []const u8, override: ?json.Value) ![]const u8 { // Fast path: no override means the run inherits the deployment defaults verbatim. if (override == null) return base_json; var arena = std.heap.ArenaAllocator.init(alloc); defer arena.deinit(); const a = arena.allocator(); const parsed_base = json.parseFromSlice(json.Value, a, base_json, .{}) catch |err| { if (err == error.OutOfMemory) return err; // Base parameters not valid JSON — use the override alone rather // than failing the whole flow-run creation. var out: std.Io.Writer.Allocating = .init(alloc); errdefer out.deinit(); var jw: json.Stringify = .{ .writer = &out.writer }; try jw.write(override.?); return out.toOwnedSlice(); }; var merged: json.ObjectMap = .empty; if (parsed_base.value == .object) { var it = parsed_base.value.object.iterator(); while (it.next()) |e| try merged.put(a, e.key_ptr.*, e.value_ptr.*); } var it = override.?.object.iterator(); while (it.next()) |e| try merged.put(a, e.key_ptr.*, e.value_ptr.*); var out: std.Io.Writer.Allocating = .init(alloc); errdefer out.deinit(); var jw: json.Stringify = .{ .writer = &out.writer }; try jw.write(json.Value{ .object = merged }); return out.toOwnedSlice(); } fn normalizeTimestamp(alloc: std.mem.Allocator, raw: []const u8) !?[]const u8 { // find space between date and time const space_idx = mem.indexOf(u8, raw, " ") orelse return raw; var normalized = try alloc.alloc(u8, raw.len); @memcpy(normalized, raw); normalized[space_idx] = 'T'; // convert +00:00 to Z if (mem.endsWith(u8, normalized, "+00:00")) { normalized[normalized.len - 6] = 'Z'; return normalized[0 .. normalized.len - 5]; } return normalized; } // Build InsertParams / UpdateParams from typed bodies. JSON-blob fields // (parameters, labels, tags, job_variables, pull_steps, parameter_openapi_schema) // are stringified once via stringifyValue; the DB columns store them as TEXT. // // concurrency_limit_id is set in a follow-up via applyConcurrencyLimit after // the deployment row exists (we need the id to name the v2 limit // "deployment:{id}"). When the client passes `global_concurrency_limit_id` // directly, we take it as-is. const empty_object_schema = \\{"type": "object", "properties": {}} ; fn buildInsertParamsFromCreate(alloc: Allocator, body: DeploymentCreateBody) !db.deployments.InsertParams { return .{ .version = body.version, .description = body.description, .paused = body.paused, .parameters = try stringifyOrDefault(alloc, body.parameters, "{}"), // python's DeploymentCreate defaults the schema to a permissive empty // object schema, so schema-less deployments validate rather than 409 .parameter_openapi_schema = if (body.parameter_openapi_schema) |v| try stringifyValue(alloc, v) else empty_object_schema, .enforce_parameter_schema = body.enforce_parameter_schema, .tags = try stringifyOrDefault(alloc, body.tags, "[]"), .labels = try stringifyOrDefault(alloc, body.labels, "{}"), .path = body.path, .entrypoint = body.entrypoint, .job_variables = try stringifyOrDefault(alloc, body.job_variables, "{}"), .pull_steps = if (body.pull_steps) |v| try stringifyValue(alloc, v) else null, .work_pool_name = body.work_pool_name, .work_queue_name = body.work_queue_name, .concurrency_limit_id = body.global_concurrency_limit_id, .concurrency_options = if (body.concurrency_options) |v| try stringifyNullableValue(alloc, v) else null, }; } // Pool names are denormalized metadata; workers route by queue UUID. // Resolve updates and upserts just as creation resolves its destination. fn resolveUpdateQueue(alloc: Allocator, params: *db.deployments.UpdateParams, now: []const u8) !void { const pool_name = params.work_pool_name orelse return; const pool = try db.work_pools.getByName(alloc, pool_name) orelse return error.WorkPoolNotFound; if (params.work_queue_name) |name| { if (try db.work_queues.getByPoolAndName(alloc, pool.id, name)) |queue| { params.work_queue_id = queue.id; } else { var id_buf: [36]u8 = undefined; const id = uuid_util.generate(runtime.appIo(), &id_buf); try db.work_queues.insert(id, name, "", false, null, 1, pool.id, .not_ready, now); params.work_queue_id = try alloc.dupe(u8, id); } } else { params.work_queue_id = pool.default_queue_id; params.work_queue_name = "default"; } } fn buildUpdateParamsFromCreate(alloc: Allocator, body: DeploymentCreateBody) !db.deployments.UpdateParams { return .{ .version = body.version, .description = body.description, .paused = body.paused, .parameters = if (body.parameters) |v| try stringifyValue(alloc, v) else null, // upserts go through DeploymentCreate in python, so an omitted schema // still lands as the empty-object default .parameter_openapi_schema = if (body.parameter_openapi_schema) |v| try stringifyValue(alloc, v) else empty_object_schema, .enforce_parameter_schema = body.enforce_parameter_schema, .tags = if (body.tags) |v| try stringifyValue(alloc, v) else null, .labels = if (body.labels) |v| try stringifyValue(alloc, v) else null, .path = body.path, .entrypoint = body.entrypoint, .job_variables = if (body.job_variables) |v| try stringifyValue(alloc, v) else null, .pull_steps = if (body.pull_steps) |v| try stringifyValue(alloc, v) else null, .work_pool_name = body.work_pool_name, .work_queue_name = body.work_queue_name, .concurrency_limit_id = body.global_concurrency_limit_id, .concurrency_options = if (body.concurrency_options) |v| try stringifyNullableValue(alloc, v) else null, }; } fn buildUpdateParamsFromUpdate(alloc: Allocator, body: DeploymentUpdateBody) !db.deployments.UpdateParams { return .{ .version = body.version, .description = body.description, .paused = body.paused, .parameters = if (body.parameters) |v| try stringifyValue(alloc, v) else null, .parameter_openapi_schema = if (body.parameter_openapi_schema) |v| try stringifyValue(alloc, v) else null, .enforce_parameter_schema = body.enforce_parameter_schema, .tags = if (body.tags) |v| try stringifyValue(alloc, v) else null, .labels = if (body.labels) |v| try stringifyValue(alloc, v) else null, .path = body.path, .entrypoint = body.entrypoint, .job_variables = if (body.job_variables) |v| try stringifyValue(alloc, v) else null, .pull_steps = if (body.pull_steps) |v| try stringifyValue(alloc, v) else null, .work_pool_name = body.work_pool_name, .work_queue_name = body.work_queue_name, .concurrency_limit_id = body.global_concurrency_limit_id, .concurrency_options = if (body.concurrency_options) |v| try stringifyNullableValue(alloc, v) else null, }; } /// Apply a `concurrency_limit: N` input by creating or updating the deployment's /// auto-managed v2 limit (name = "deployment:{deployment_id}"). Mirrors python's /// `_create_or_update_deployment_concurrency_limit`. Sets `deployment.concurrency_limit_id`. /// /// Pass `null` to clear (deletes the auto-managed v2 limit and unsets the FK). fn applyConcurrencyLimit(alloc: std.mem.Allocator, deployment_id: []const u8, requested_limit: ?i64) !void { var name_buf: [128]u8 = undefined; const name = try std.fmt.bufPrint(&name_buf, "deployment:{s}", .{deployment_id}); var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf); const existing = try db.concurrency_limits.getByName(alloc, name); if (requested_limit) |limit| { if (existing) |row| { // Update existing auto-managed limit _ = try db.concurrency_limits.updateByName(name, null, limit, null, null, null, null, null, now); _ = try db.deployments.setConcurrencyLimitId(deployment_id, now, row.id); } else { // Create new auto-managed limit var id_buf: [36]u8 = undefined; const new_id = uuid_util.generate(runtime.appIo(), &id_buf); try db.concurrency_limits.insert(new_id, name, limit, true, 0, 0, 0.0, 2.0, now); _ = try db.deployments.setConcurrencyLimitId(deployment_id, now, new_id); } } else { // requested_limit == null → clear. Delete the auto-managed limit if it // was ours. Don't touch a directly-set global_concurrency_limit_id. if (existing) |_| _ = try db.concurrency_limits.deleteByName(name); _ = try db.deployments.setConcurrencyLimitId(deployment_id, now, null); } } fn applyConcurrencyOptions(alloc: std.mem.Allocator, deployment_id: []const u8, options: json.Value, now: []const u8) !void { _ = try db.deployments.setConcurrencyOptions( deployment_id, now, try stringifyNullableValue(alloc, options), ); } // Response serializers fn writeDeployment(alloc: std.mem.Allocator, d: db.deployments.DeploymentRow) ![]const u8 { var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; try writeDeploymentObject(&jw, d, alloc); return output.toOwnedSlice(); } fn writeDeploymentObject(jw: *json.Stringify, d: db.deployments.DeploymentRow, alloc: std.mem.Allocator) !void { try jw.beginObject(); try jw.objectField("id"); try jw.write(d.id); try jw.objectField("created"); try jw.write(d.created); try jw.objectField("updated"); try jw.write(d.updated); try jw.objectField("name"); try jw.write(d.name); try jw.objectField("flow_id"); try jw.write(d.flow_id); try jw.objectField("version"); try jw.write(d.version); try jw.objectField("description"); try jw.write(d.description); try jw.objectField("paused"); try jw.write(d.paused); try jw.objectField("status"); try jw.write(d.status.toString()); try jw.objectField("last_polled"); try jw.write(d.last_polled); try jw.objectField("parameters"); try jw.beginWriteRaw(); try jw.writer.writeAll(d.parameters); jw.endWriteRaw(); try jw.objectField("parameter_openapi_schema"); if (d.parameter_openapi_schema) |s| { try jw.beginWriteRaw(); try jw.writer.writeAll(s); jw.endWriteRaw(); } else { try jw.write(null); } try jw.objectField("enforce_parameter_schema"); try jw.write(d.enforce_parameter_schema); try jw.objectField("tags"); try jw.beginWriteRaw(); try jw.writer.writeAll(d.tags); jw.endWriteRaw(); try jw.objectField("labels"); try jw.beginWriteRaw(); try jw.writer.writeAll(d.labels); jw.endWriteRaw(); try jw.objectField("path"); try jw.write(d.path); try jw.objectField("entrypoint"); try jw.write(d.entrypoint); try jw.objectField("job_variables"); try jw.beginWriteRaw(); try jw.writer.writeAll(d.job_variables); jw.endWriteRaw(); try jw.objectField("pull_steps"); if (d.pull_steps) |ps| { try jw.beginWriteRaw(); try jw.writer.writeAll(ps); jw.endWriteRaw(); } else { try jw.write(null); } try jw.objectField("work_pool_name"); try jw.write(d.work_pool_name); try jw.objectField("work_queue_name"); try jw.write(d.work_queue_name); try jw.objectField("work_queue_id"); try jw.write(d.work_queue_id); try jw.objectField("storage_document_id"); try jw.write(d.storage_document_id); try jw.objectField("infrastructure_document_id"); try jw.write(d.infrastructure_document_id); try jw.objectField("concurrency_limit_id"); try jw.write(d.concurrency_limit_id); // Derive the integer `concurrency_limit` from the linked v2 limit so the // response matches python's Deployment shape. Falls back to null if the // FK is unset OR the row was deleted. try jw.objectField("concurrency_limit"); if (d.concurrency_limit_id) |cl_id| { if (try db.concurrency_limits.getById(alloc, cl_id)) |cl| { try jw.write(cl.limit); } else { try jw.write(null); } } else { try jw.write(null); } try jw.objectField("concurrency_options"); if (d.concurrency_options) |options| { try jw.beginWriteRaw(); try jw.writer.writeAll(options); jw.endWriteRaw(); } else { try jw.write(null); } try jw.objectField("schedules"); const sched_list = try db.deployment_schedules.listByDeployment(alloc, d.id); try jw.beginArray(); for (sched_list) |s| { try schedules.writeScheduleObject(jw, s); } try jw.endArray(); try jw.endObject(); } fn writeFlowRunObject(jw: *json.Stringify, run: db.flow_runs.FlowRunRow, 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_id"); try jw.write(run.flow_id); try jw.objectField("deployment_id"); try jw.write(run.deployment_id); try jw.objectField("deployment_version"); try jw.write(run.deployment_version); try jw.objectField("work_queue_name"); try jw.write(run.work_queue_name); try jw.objectField("work_queue_id"); try jw.write(run.work_queue_id); 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("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("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); try jw.objectField("id"); try jw.write(state_id); try jw.endObject(); try jw.objectField("parameters"); try jw.beginWriteRaw(); try jw.writer.writeAll(run.parameters); jw.endWriteRaw(); try jw.objectField("tags"); try jw.beginWriteRaw(); try jw.writer.writeAll(run.tags); jw.endWriteRaw(); try jw.objectField("auto_scheduled"); try jw.write(run.auto_scheduled); try jw.endObject(); } fn writeFlowRunResponse(alloc: std.mem.Allocator, run: db.flow_runs.FlowRunRow, state_id: []const u8) ![]const u8 { var output: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &output.writer }; 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_id"); try jw.write(run.flow_id); try jw.objectField("deployment_id"); try jw.write(run.deployment_id); try jw.objectField("idempotency_key"); try jw.write(run.idempotency_key); try jw.objectField("deployment_version"); try jw.write(run.deployment_version); try jw.objectField("work_queue_name"); try jw.write(run.work_queue_name); try jw.objectField("work_queue_id"); try jw.write(run.work_queue_id); 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); try jw.objectField("id"); try jw.write(state_id); try jw.endObject(); try jw.objectField("parameters"); try jw.beginWriteRaw(); try jw.writer.writeAll(run.parameters); jw.endWriteRaw(); try jw.objectField("tags"); try jw.beginWriteRaw(); try jw.writer.writeAll(run.tags); jw.endWriteRaw(); try jw.objectField("auto_scheduled"); try jw.write(run.auto_scheduled); try jw.endObject(); return output.toOwnedSlice(); } 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 "deployment parameter merge cannot discard overrides on allocation failure" { const Check = struct { fn run(alloc: Allocator) !void { const override = try json.parseFromSlice(json.Value, std.testing.allocator, "{\"shared\":\"override\",\"new\":[1,true]}", .{}); defer override.deinit(); const output = mergeParameters(alloc, "{\"shared\":\"base\",\"keep\":42}", override.value) catch |err| return switch (err) { error.WriteFailed => error.OutOfMemory, else => err, }; defer alloc.free(output); const parsed = try json.parseFromSlice(json.Value, std.testing.allocator, output, .{}); defer parsed.deinit(); const obj = parsed.value.object; try std.testing.expectEqualStrings("override", obj.get("shared").?.string); try std.testing.expectEqual(@as(i64, 42), obj.get("keep").?.integer); try std.testing.expectEqual(@as(usize, 2), obj.get("new").?.array.items.len); } }; try std.testing.checkAllAllocationFailures(std.testing.allocator, Check.run, .{}); } test "request allocation failure is not a validation response" { try @import("response_test.zig").expectRequestAllocationError(handle, "/api/deployments/", "{\"flow_id\": \"00000000-0000-4000-8000-000000000001\", \"name\": \"x\"}"); } test "hydration database failure propagates before creating a flow run" { const backend = @import("../db/backend.zig"); backend.db = try backend.Backend.initSqlite(std.testing.allocator, ":memory:"); defer backend.db.deinit(); try @import("../db/schema/sqlite.zig").init(); const flow_id = "00000000-0000-4000-8000-000000000001"; const deployment_id = "00000000-0000-4000-8000-000000000002"; try db.flows.insert(flow_id, "hydration-fault"); try db.deployments.insert(deployment_id, "hydration-fault", flow_id, "2026-10-12T00:00:00Z", .{ .parameters = "{\"x\":{\"__prefect_kind\":\"workspace_variable\",\"variable_name\":\"answer\"}}", .enforce_parameter_schema = false, }); try db.variables.insert("00000000-0000-4000-8000-000000000003", "answer", "42", "[]", "2026-10-12T00:00:00Z"); var lookup_arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer lookup_arena.deinit(); const variable = (try db.variables.getByName(lookup_arena.allocator(), "answer")).?; try std.testing.expectEqualStrings("42", variable.value); try backend.db.exec("ALTER TABLE variable RENAME TO unavailable_variable", .{}); var request = @import("httpz").testing.init(.{}); defer request.deinit(); request.url("/api/deployments/" ++ deployment_id ++ "/create_flow_run"); var req = wap.Request.from(request.req); var res: wap.Response = .{ .inner = request.res, .arena = req.arena }; try std.testing.expectError(error.Error, createFlowRun(&req, &res, req.path)); try std.testing.expect(!res.is_sent); { var row = (try backend.db.row("SELECT COUNT(*) FROM flow_run", .{})).?; defer row.deinit(); try std.testing.expectEqual(@as(i64, 0), row.int(0)); } try backend.db.exec("ALTER TABLE unavailable_variable RENAME TO variable", .{}); try createFlowRun(&req, &res, req.path); try std.testing.expect(res.is_sent); var persisted = (try backend.db.row("SELECT parameters FROM flow_run", .{})).?; defer persisted.deinit(); const parameters = try json.parseFromSlice(json.Value, std.testing.allocator, persisted.text(0), .{}); defer parameters.deinit(); try std.testing.expectEqual(@as(i64, 42), parameters.value.object.get("x").?.integer); }