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 BlockDocumentCreate / Update ===== const BlockDocumentCreateBody = struct { block_type_id: []const u8, block_schema_id: []const u8, name: ?[]const u8 = null, data: ?json.Value = null, is_anonymous: ?bool = null, }; const BlockDocumentUpdateBody = struct { block_schema_id: ?[]const u8 = null, data: ?json.Value = null, merge_existing_data: bool = true, }; fn corsHeaders(res: *wap.Response) void { _ = res.setHeader("access-control-allow-origin", "*"); _ = res.setHeader("access-control-allow-methods", "GET, POST, PATCH, DELETE, OPTIONS"); _ = res.setHeader("access-control-allow-headers", "content-type, x-prefect-api-version"); } fn sendValidationError(res: *wap.Response, detail: []const u8) !void { corsHeaders(res); _ = res.setStatus(.unprocessable_entity); try res.writeJson(.{ .detail = detail }); } fn sendError(res: *wap.Response, status: std.http.Status, detail: []const u8) !void { corsHeaders(res); _ = res.setStatus(status); try res.writeJson(.{ .detail = detail }); } 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(); } // Routes: // POST /block_documents/ - create // GET /block_documents/{id} - read by id // PATCH /block_documents/{id} - update // DELETE /block_documents/{id} - delete // POST /block_documents/filter - list pub fn handle(req: *wap.Request, res: *wap.Response) !void { const target = req.path; const method = @tagName(req.method); // strip /api prefix if present const path = if (mem.startsWith(u8, target, "/api/block_documents")) target[4..] else target; // POST /block_documents/filter if (mem.eql(u8, method, "POST") and mem.endsWith(u8, path, "/filter")) { try filter(req, res); return; } // POST /block_documents/count if (mem.eql(u8, method, "POST") and mem.endsWith(u8, path, "/count")) { try count(res); return; } // POST /block_documents/ - create if (mem.eql(u8, method, "POST") and (mem.eql(u8, path, "/block_documents/") or mem.eql(u8, path, "/block_documents"))) { try create(req, res); return; } // GET /block_documents/{id} or PATCH /block_documents/{id} or DELETE /block_documents/{id} if (mem.startsWith(u8, path, "/block_documents/")) { const id = path["/block_documents/".len..]; if (id.len >= 32) { if (mem.eql(u8, method, "GET")) { try getById(req, res, id); return; } else if (mem.eql(u8, method, "PATCH")) { try update(req, res, id); return; } else if (mem.eql(u8, method, "DELETE")) { try delete(res, id); return; } } } try sendError(res, .not_found, "not found"); } fn create(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena; const body = req.parseJson(BlockDocumentCreateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; // python's BlockDocumentCreate: is_anonymous defaults to (name == None) const is_anonymous = body.is_anonymous orelse (body.name == null); // data is opaque JSON — stringify for storage const data: []const u8 = if (body.data) |v| try stringifyValue(alloc, v) else "{}"; const bt = try db.block_types.getById(alloc, body.block_type_id); const block_type_name = if (bt) |t| t.name else null; // Older databases may predate the UNIQUE(block_type_id, name) // constraint in the current schema. Preserve Prefect's create-conflict- // overwrite contract at the API boundary too, so Secret.save(..., // overwrite=true) reaches PATCH instead of creating an unreachable // duplicate document. if (body.name) |name| { if (try db.block_documents.getByTypeIdAndName(alloc, body.block_type_id, name) != null) { try sendError(res, .conflict, "Block already exists"); return; } } var id_buf: [36]u8 = undefined; const id = uuid_util.generate(runtime.appIo(), &id_buf); db.block_documents.insert(id, body.name, data, is_anonymous, body.block_type_id, block_type_name, body.block_schema_id) catch |err| { if (err == error.Constraint) { try sendError(res, .conflict, "Block already exists"); return; } 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 doc = db.block_documents.BlockDocumentRow{ .id = id, .created = now, .updated = now, .name = body.name, .data = data, .is_anonymous = is_anonymous, .block_type_id = body.block_type_id, .block_type_name = block_type_name, .block_schema_id = body.block_schema_id, }; const bs = try db.block_schemas.getById(alloc, body.block_schema_id); try sendBlockDocumentResponse(res, alloc, doc, bt, bs, true, .created); } fn getById(req: *wap.Request, res: *wap.Response, id: []const u8) !void { const alloc = req.arena; const doc = try db.block_documents.getById(alloc, id) orelse { try sendError(res, .not_found, "block document not found"); return; }; const bt = try db.block_types.getById(alloc, doc.block_type_id); const bs = try db.block_schemas.getById(alloc, doc.block_schema_id); try sendBlockDocumentResponse(res, alloc, doc, bt, bs, try includeSecrets(req), .ok); } fn update(req: *wap.Request, res: *wap.Response, id: []const u8) !void { const alloc = req.arena; const body = req.parseJson(BlockDocumentUpdateBody) catch |err| { return switch (err) { error.OutOfMemory => return err, error.UnknownField => sendValidationError(res, "unknown field in request body"), else => sendValidationError(res, "invalid json"), }; }; // Compute final data to store: if merge_existing_data is true (default), // overlay new keys onto the existing document's data; else replace. const data: ?[]const u8 = blk: { const new_val = body.data orelse break :blk null; if (body.merge_existing_data) { const current = try db.block_documents.getById(alloc, id) orelse { try sendError(res, .not_found, "Block document not found"); return; }; const current_parsed = json.parseFromSlice(json.Value, alloc, current.data, .{}) catch |err| { if (err == error.OutOfMemory) return err; break :blk try stringifyValue(alloc, new_val); }; defer current_parsed.deinit(); if (current_parsed.value == .object and new_val == .object) { var current_obj = current_parsed.value.object; var it = new_val.object.iterator(); while (it.next()) |entry| { try current_obj.put(alloc, entry.key_ptr.*, entry.value_ptr.*); } break :blk try stringifyValue(alloc, json.Value{ .object = current_obj }); } break :blk try stringifyValue(alloc, new_val); } break :blk try stringifyValue(alloc, new_val); }; if (data == null and body.block_schema_id == null) { try res.sendEmpty(.no_content); return; } const updated = db.block_documents.update(id, data orelse "{}", body.block_schema_id) catch { try sendError(res, .internal_server_error, "update failed"); return; }; if (!updated) { try sendError(res, .not_found, "Block document not found"); return; } try res.sendEmpty(.no_content); } fn delete(res: *wap.Response, id: []const u8) !void { const deleted = db.block_documents.delete(id) catch { try sendError(res, .internal_server_error, "delete failed"); return; }; if (!deleted) { try sendError(res, .not_found, "Block document not found"); return; } try res.sendEmpty(.no_content); } fn filter(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena; const docs = db.block_documents.list(alloc, 200) 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; }; const include_secrets = try includeSecrets(req); for (docs) |doc| { try writeBlockDocument(&jw, doc, include_secrets); } try jw.endArray(); corsHeaders(res); _ = res.setHeader("content-type", "application/json"); try res.sendBody(try output.toOwnedSlice()); } fn count(res: *wap.Response) !void { const total = db.block_documents.count() catch { try sendError(res, .internal_server_error, "database error"); return; }; corsHeaders(res); _ = res.setHeader("content-type", "application/json"); try res.writeJson(total); } fn writeBlockDocument(jw: *json.Stringify, doc: db.block_documents.BlockDocumentRow, include_secrets: bool) !void { try jw.beginObject(); try jw.objectField("id"); try jw.write(doc.id); try jw.objectField("created"); try jw.write(doc.created); try jw.objectField("updated"); try jw.write(doc.updated); try jw.objectField("name"); try jw.write(doc.name); try jw.objectField("data"); try writeDocumentData(jw, doc, null, include_secrets); try jw.objectField("is_anonymous"); try jw.write(doc.is_anonymous); try jw.objectField("block_type_id"); try jw.write(doc.block_type_id); try jw.objectField("block_schema_id"); try jw.write(doc.block_schema_id); try jw.endObject(); } fn sendBlockDocumentResponse(res: *wap.Response, alloc: std.mem.Allocator, doc: db.block_documents.BlockDocumentRow, bt: ?db.block_types.BlockTypeRow, bs: ?db.block_schemas.BlockSchemaRow, include_secrets: bool, status: std.http.Status) !void { var output: std.Io.Writer.Allocating = .init(alloc); defer output.deinit(); var jw: json.Stringify = .{ .writer = &output.writer }; try jw.beginObject(); try jw.objectField("id"); try jw.write(doc.id); try jw.objectField("created"); try jw.write(doc.created); try jw.objectField("updated"); try jw.write(doc.updated); try jw.objectField("name"); try jw.write(doc.name); try jw.objectField("data"); try writeDocumentData(&jw, doc, bt, include_secrets); try jw.objectField("is_anonymous"); try jw.write(doc.is_anonymous); try jw.objectField("block_type_id"); try jw.write(doc.block_type_id); try jw.objectField("block_schema_id"); try jw.write(doc.block_schema_id); try jw.objectField("block_type"); if (bt) |t| { try jw.beginObject(); try jw.objectField("id"); try jw.write(t.id); try jw.objectField("created"); try jw.write(t.created); try jw.objectField("updated"); try jw.write(t.updated); try jw.objectField("name"); try jw.write(t.name); try jw.objectField("slug"); try jw.write(t.slug); try jw.objectField("logo_url"); try jw.write(t.logo_url); try jw.objectField("documentation_url"); try jw.write(t.documentation_url); try jw.objectField("description"); try jw.write(t.description); try jw.objectField("code_example"); try jw.write(t.code_example); try jw.objectField("is_protected"); try jw.write(t.is_protected); try jw.endObject(); } else { try jw.write(null); } try jw.objectField("block_schema"); if (bs) |s| { try jw.beginObject(); try jw.objectField("id"); try jw.write(s.id); try jw.objectField("created"); try jw.write(s.created); try jw.objectField("updated"); try jw.write(s.updated); try jw.objectField("checksum"); try jw.write(s.checksum); try jw.objectField("fields"); try jw.beginWriteRaw(); try jw.writer.writeAll(s.fields); jw.endWriteRaw(); try jw.objectField("capabilities"); try jw.beginWriteRaw(); try jw.writer.writeAll(s.capabilities); jw.endWriteRaw(); try jw.objectField("version"); try jw.write(s.version); try jw.objectField("block_type_id"); try jw.write(s.block_type_id); try jw.endObject(); } else { try jw.write(null); } try jw.objectField("block_document_references"); try jw.beginObject(); try jw.endObject(); try jw.endObject(); corsHeaders(res); _ = res.setStatus(status); _ = res.setHeader("content-type", "application/json"); try res.sendBody(output.written()); } fn includeSecrets(req: *wap.Request) !bool { if (req.queryParam("include_secrets")) |raw| return parseBool(raw); if (req.body.len == 0) return false; const parsed = req.parseJsonValue() catch |err| switch (err) { error.OutOfMemory => return err, else => return false, }; if (parsed != .object) return false; const value = parsed.object.get("include_secrets") orelse return false; return value == .bool and value.bool; } fn parseBool(raw: []const u8) bool { return std.ascii.eqlIgnoreCase(raw, "true") or mem.eql(u8, raw, "1"); } fn isSecretDocument(doc: db.block_documents.BlockDocumentRow, bt: ?db.block_types.BlockTypeRow) bool { if (bt) |t| { if (mem.eql(u8, t.slug, "secret")) return true; if (mem.eql(u8, t.name, "Secret")) return true; } if (doc.block_type_name) |name| { if (mem.eql(u8, name, "Secret")) return true; if (mem.eql(u8, name, "secret")) return true; } return false; } fn writeDocumentData(jw: *json.Stringify, doc: db.block_documents.BlockDocumentRow, bt: ?db.block_types.BlockTypeRow, include_secrets: bool) !void { if (!include_secrets and isSecretDocument(doc, bt)) { try jw.beginObject(); try jw.objectField("value"); try jw.write("**********"); try jw.endObject(); return; } try jw.beginWriteRaw(); try jw.writer.writeAll(doc.data); jw.endWriteRaw(); } test "block document serialization propagates allocation failure without sending partial JSON" { const Check = struct { fn send(res: *wap.Response, alloc: Allocator) !void { try sendBlockDocumentResponse(res, alloc, @import("response_test.zig").document, null, null, true, .ok); } }; try @import("response_test.zig").checkJsonResponse(Check.send); } 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/block_documents/", "{\"name\": \"x\", \"block_type_id\": \"00000000-0000-4000-8000-000000000001\", \"block_schema_id\": \"00000000-0000-4000-8000-000000000002\", \"data\": {}}"); }