Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336const std = @import("std");const wap = @import("wap");const json = std.json;const observability = @import("../observability.zig");const runtime = @import("../runtime.zig");const backend = @import("../db/backend.zig");const db = @import("../db/sqlite.zig");const env = @import("../utilities/env.zig");const uuid_util = @import("../utilities/uuid.zig");const time_util = @import("../utilities/time.zig");const mem = std.mem;
/// Key used by python's prefect.server.models.storage_defaults — keep parity/// so a future cross-engine migration finds the row by name.const STORAGE_KEY = "server-default-result-storage";
pub fn health(_: *wap.Request, res: *wap.Response) !void { corsHeaders(res); try res.writeJson(true);}
/// `GET /api/hello` — python returns the string "👋". Mirror that.pub fn hello(_: *wap.Request, res: *wap.Response) !void { corsHeaders(res); try res.writeJson("👋");}
/// `GET /api/ready` — DB connectivity check. 200 {"message":"OK"} when the/// backend can serve a trivial query, else 503 {"message":"Database is not/// available"}. Mirrors python's `perform_readiness_check`.pub fn ready(_: *wap.Request, res: *wap.Response) !void { corsHeaders(res); var rows = backend.db.query("SELECT 1", .{}) catch { _ = res.setStatus(.service_unavailable); try res.writeJson(.{ .message = "Database is not available" }); return; }; rows.deinit(); try res.writeJson(.{ .message = "OK" });}
/// `GET /api/admin/settings` — python returns the full Settings tree with/// secrets obfuscated. The only field any caller in the python codebase/// actually reads is `server.analytics_enabled` (analytics service); the SDK/// otherwise just stashes the response. Return the minimal shape that keeps/// analytics opt-out semantics correct.pub fn settings(_: *wap.Request, res: *wap.Response) !void { corsHeaders(res); try res.writeJson(.{ .server = .{ .analytics_enabled = false, .ui = .{ .show_promotional_content = showPromotionalContent(), }, }, });}
fn showPromotionalContent() bool { const raw = env.getenv("PREFECT_SERVER_UI_SHOW_PROMOTIONAL_CONTENT") orelse return true; return parseBool(raw);}
fn parseBool(raw: []const u8) bool { const trimmed = std.mem.trim(u8, raw, " \t\r\n"); return std.mem.eql(u8, trimmed, "1") or std.ascii.eqlIgnoreCase(trimmed, "true") or std.ascii.eqlIgnoreCase(trimmed, "yes") or std.ascii.eqlIgnoreCase(trimmed, "on");}
pub fn csrfToken(req: *wap.Request, res: *wap.Response) !void { corsHeaders(res); // prefect client expects a csrf token with client id and expiration. const client_id = req.queryParam("client") orelse "unknown"; try res.writeJson(.{ .token = "zig-csrf-token", .client = client_id, .expiration = "2099-01-01T00:00:00Z", });}
/// `GET /ui-settings` (and legacy `/api/ui-settings`) — runtime configuration/// consumed by the Prefect SPA. When a UI bundle is served from/// PREFECT_UI_STATIC_DIR, this tells it to use this server's API.pub fn uiSettings(req: *wap.Request, res: *wap.Response) !void { corsHeaders(res); const v2_base_url = try normalizeUiBaseUrl(req.arena, uiServeBase()); const auth: ?[]const u8 = if (serverApiAuthString() != null) "BASIC" else null; try res.writeJson(.{ .api_url = uiApiUrl(), .csrf_enabled = false, .auth = auth, .flags = &[_][]const u8{}, .default_ui = "v2", .available_uis = &[_][]const u8{"v2"}, .v1_base_url = null, .v2_base_url = v2_base_url, });}
fn uiApiUrl() []const u8 { return env.getenv("PREFECT_UI_API_URL") orelse env.getenv("PREFECT_SERVER_UI_API_URL") orelse "/api";}
fn uiServeBase() []const u8 { return env.getenv("PREFECT_UI_SERVE_BASE") orelse env.getenv("PREFECT_SERVER_UI_SERVE_BASE") orelse "/";}
fn serverApiAuthString() ?[]const u8 { return env.getenv("PREFECT_SERVER_API_AUTH_STRING") orelse env.getenv("PREFECT_API_AUTH_STRING");}
fn normalizeUiBaseUrl(alloc: std.mem.Allocator, raw: []const u8) ![]const u8 { const trimmed = std.mem.trim(u8, raw, " \t\r\n"); if (trimmed.len == 0 or std.mem.eql(u8, trimmed, "/")) return "/";
const with_leading = if (trimmed[0] == '/') trimmed else try std.fmt.allocPrint(alloc, "/{s}", .{trimmed});
var end = with_leading.len; while (end > 1 and with_leading[end - 1] == '/') end -= 1; return with_leading[0..end];}
fn joinUiPath(alloc: std.mem.Allocator, base_url: []const u8, suffix: []const u8) ![]const u8 { const normalized_base = try normalizeUiBaseUrl(alloc, base_url); const normalized_suffix = std.mem.trimStart(u8, suffix, "/"); if (std.mem.eql(u8, normalized_base, "/")) { return try std.fmt.allocPrint(alloc, "/{s}", .{normalized_suffix}); } return try std.fmt.allocPrint(alloc, "{s}/{s}", .{ normalized_base, normalized_suffix });}
test "resolveUiBaseUrls matches python serve_base shape" { const alloc = std.testing.allocator; const root = try resolveUiBaseUrls(alloc, "/"); defer alloc.free(root.v2); try std.testing.expectEqualStrings("/", root.v1); try std.testing.expectEqualStrings("/v2", root.v2);
const prefect = try resolveUiBaseUrls(alloc, "/prefect"); defer alloc.free(prefect.v2); try std.testing.expectEqualStrings("/prefect", prefect.v1); try std.testing.expectEqualStrings("/prefect/v2", prefect.v2);
const v2 = try resolveUiBaseUrls(alloc, "/prefect/v2/"); try std.testing.expectEqualStrings("/prefect", v2.v1); try std.testing.expectEqualStrings("/prefect/v2", v2.v2);}
fn resolveUiBaseUrls(alloc: std.mem.Allocator, configured_base_url: []const u8) !struct { v1: []const u8, v2: []const u8 } { const normalized_base = try normalizeUiBaseUrl(alloc, configured_base_url); const v2_suffix = "/v2";
if (std.mem.eql(u8, normalized_base, v2_suffix)) { return .{ .v1 = "/", .v2 = normalized_base }; } if (std.mem.endsWith(u8, normalized_base, v2_suffix)) { const v1 = normalized_base[0 .. normalized_base.len - v2_suffix.len]; return .{ .v1 = if (v1.len == 0) "/" else v1, .v2 = normalized_base }; } return .{ .v1 = normalized_base, .v2 = try joinUiPath(alloc, normalized_base, "v2"), };}
pub fn version(_: *wap.Request, res: *wap.Response) !void { corsHeaders(res); // FastAPI returns the version as a JSON string. Python prefect client // warns if its own version > the server's, so report a value matching // the python prefect we sync to. Set at build time via // -Dprefect_compat_version (see build.zig); bump on each sync. try res.writeJson(observability.getPrefectCompatVersion());}
/// `GET /api/version` — this server's own version and build.////// Python serves its frozen `SERVER_API_VERSION` ("0.8.4" since 2022) here./// We deliberately do not echo that: it identifies nothing, and no client/// compares a server's response to it. See the note in build.zig. The prefect/// release we claim compat with is at /admin/version, which clients do read.pub fn apiVersion(_: *wap.Request, res: *wap.Response) !void { corsHeaders(res); try res.writeJson(observability.getServerVersion());}
fn corsHeaders(res: *wap.Response) void { _ = res.setHeader("access-control-allow-origin", "*") .setHeader("access-control-allow-methods", "GET, POST, PATCH, DELETE, OPTIONS") .setHeader("access-control-allow-headers", "authorization, content-type, prefect-api-version, prefect-csrf-token, prefect-csrf-client, x-prefect-api-version") .setHeader("access-control-allow-private-network", "true");}
/// `/metrics` — prometheus text format. Scraped by `scripts/profile-load`/// and any external prometheus. Mirrors the surface zlay exposes from its/// MetricsServer.handleMetricsConn — see ~/tangled.org/zzstoatzz.io/zlay/src/main.zig.pub fn metrics(_: *wap.Request, res: *wap.Response) !void { const alloc = res.arena;
var buf: std.Io.Writer.Allocating = .init(alloc); writeAll(&buf.writer) catch { _ = res.setStatus(.internal_server_error) .setHeader("content-type", "text/plain"); try res.sendBody("metrics formatter failed\n"); return; };
const body = buf.written(); _ = res.setHeader("content-type", "text/plain; version=0.0.4; charset=utf-8") .setHeader("access-control-allow-origin", "*"); try res.sendBody(body);}
fn writeAll(writer: *std.Io.Writer) !void { try observability.writeMetrics(writer, runtime.appIo()); try db.metrics.write(writer);}
// ===== /api/admin/storage =====//// Server default result storage block. Flows that don't declare their own// result storage use this. Mirrors python's// `prefect.server.api.admin.{read,update,clear}_server_default_result_storage`,// backed by the same single-row-in-`configuration` pattern (key// `server-default-result-storage`, value = full ServerDefaultResultStorage// JSON). Also surfaced in WorkPoolSnapshot.storage_configuration.
const StoragePut = struct { default_result_storage_block_id: ?[]const u8 = null,};
/// Dispatch GET / PUT / DELETE for /api/admin/storage.pub fn storage(req: *wap.Request, res: *wap.Response) !void { switch (req.method) { .GET => try storageGet(res), .PUT => try storagePut(req, res), .DELETE => try storageDelete(res), else => { _ = res.setStatus(.method_not_allowed); try res.writeJson(.{ .detail = "method not allowed" }); }, }}
fn storageGet(res: *wap.Response) !void { const alloc = res.arena;
const value = try db.configuration.read(alloc, STORAGE_KEY); if (value) |raw| { // value is a complete JSON object — emit it verbatim with the right // content-type rather than re-parsing. _ = res.setHeader("content-type", "application/json"); try res.sendBody(raw); return; } // python returns the default-constructed model when no row exists, i.e. // `{"default_result_storage_block_id": null}`. Match that. try res.writeJson(.{ .default_result_storage_block_id = null });}
fn storagePut(req: *wap.Request, res: *wap.Response) !void { const alloc = req.arena;
const body = req.parseJson(StoragePut) catch |err| { _ = res.setStatus(.unprocessable_entity); try res.writeJson(.{ .detail = if (err == error.UnknownField) "unknown field" else "invalid json" }); return; };
// Validate the block_document exists and has write-path capability — // mirrors python's `validate_server_default_result_storage_block`. Null // means "no default"; treat as clear-via-PUT, matching python's // model_dump(mode="json") behavior. if (body.default_result_storage_block_id) |block_id| { const block = try db.block_documents.getById(alloc, block_id); if (block == null) { _ = res.setStatus(.not_found); try res.writeJson(.{ .detail = "Block document not found" }); return; } }
var value_buf: std.Io.Writer.Allocating = .init(alloc); var jw: json.Stringify = .{ .writer = &value_buf.writer }; try jw.beginObject(); try jw.objectField("default_result_storage_block_id"); if (body.default_result_storage_block_id) |b| try jw.write(b) else try jw.write(null); try jw.endObject(); const value_json = try value_buf.toOwnedSlice();
var id_buf: [36]u8 = undefined; const id = uuid_util.generate(runtime.appIo(), &id_buf); var ts_buf: [32]u8 = undefined; const now = time_util.timestamp(runtime.appIo(), &ts_buf);
db.configuration.write(id, STORAGE_KEY, value_json, now) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "failed to persist storage setting" }); return; };
_ = res.setHeader("content-type", "application/json"); try res.sendBody(value_json);}
fn storageDelete(res: *wap.Response) !void { _ = db.configuration.delete(STORAGE_KEY) catch { _ = res.setStatus(.internal_server_error); try res.writeJson(.{ .detail = "failed to clear storage setting" }); return; }; try res.sendEmpty(.no_content);}
/// Read the current default_result_storage_block_id (or null), used by/// work_pool snapshot serialization. Cheap enough to call per-snapshot — it/// hits a single indexed row. Returns the bare UUID string or null; caller/// owns the bytes via `alloc`.pub fn readDefaultStorageBlockId(alloc: std.mem.Allocator) !?[]const u8 { const raw = (try db.configuration.read(alloc, STORAGE_KEY)) orelse return null; const parsed = json.parseFromSliceLeaky(json.Value, alloc, raw, .{}) catch |err| switch (err) { error.OutOfMemory => return err, else => return null, }; if (parsed != .object) return null; const v = parsed.object.get("default_result_storage_block_id") orelse return null; return switch (v) { .string => |s| try alloc.dupe(u8, s), else => null, };}