Something went wrong. Try again.
prefect server in zig
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244const std = @import("std");const httpz = @import("httpz");
pub const Headers = struct { keys: []const []const u8, values: []const []const u8,
pub fn get(self: Headers, name: []const u8) ?[]const u8 { for (self.keys, self.values) |k, v| { if (std.ascii.eqlIgnoreCase(k, name)) return v; } return null; }
pub const Iterator = struct { keys: []const []const u8, values: []const []const u8, pos: usize = 0,
pub const Entry = struct { name: []const u8, value: []const u8 };
pub fn next(self: *Iterator) ?Entry { if (self.pos == self.keys.len) return null; const e = Entry{ .name = self.keys[self.pos], .value = self.values[self.pos] }; self.pos += 1; return e; } };
pub fn iterator(self: Headers) Iterator { return .{ .keys = self.keys, .values = self.values }; }};
pub const Request = struct { method: std.http.Method, target: []const u8, path: []const u8, query: ?[]const u8, body: []const u8, headers: Headers, arena: std.mem.Allocator, /// Diagnostic identity for the live HTTP transport. Handlers must not use /// this for ownership; it exists so response-integrity incidents can /// correlate routing and socket writes. connection_fd: i32 = -1,
pub fn header(self: *const Request, name: []const u8) ?[]const u8 { return self.headers.get(name); }
pub fn queryParam(self: *const Request, key: []const u8) ?[]const u8 { const q = self.query orelse return null; var iter = std.mem.splitScalar(u8, q, '&'); while (iter.next()) |pair| { if (std.mem.indexOfScalar(u8, pair, '=')) |eq| { if (std.mem.eql(u8, pair[0..eq], key)) return pair[eq + 1 ..]; } else if (std.mem.eql(u8, pair, key)) { return ""; } } return null; }
/// Parse the request body as JSON into a typed struct. /// /// Rejects unknown fields with `error.UnknownField`. This matches /// python prefect's `ActionBaseModel` (`extra="forbid"`) — every /// Create/Update action in `prefect/server/schemas/actions.py` /// returns 422 on extra inputs. Doing the same here keeps the wire /// contract identical for clients written against either server. /// /// If a handler genuinely needs to accept arbitrary keys (filter /// blobs, raw config bodies), call `parseJsonValue` instead — that's /// the explicit opt-out, not a flag on this function. pub fn parseJson(self: *const Request, comptime T: type) !T { return std.json.parseFromSliceLeaky(T, self.arena, self.body, .{ .ignore_unknown_fields = false, .allocate = .alloc_always, }); }
/// Parse the request body as a freeform std.json.Value. Use only when /// the body shape is genuinely arbitrary (e.g. a filter blob with /// caller-defined keys). Prefer parseJson(T) elsewhere. pub fn parseJsonValue(self: *const Request) !std.json.Value { const parsed = try std.json.parseFromSliceLeaky(std.json.Value, self.arena, self.body, .{}); return parsed; }
/// Adapter: populate the field-shape Request handlers expect from a /// live httpz.Request. No allocations beyond what httpz already did. pub fn from(inner: *httpz.Request) Request { return .{ .method = mapMethod(inner.method), .target = inner.url.raw, .path = inner.url.path, .query = if (inner.url.query.len == 0) null else inner.url.query, .body = inner.body() orelse "", .headers = .{ .keys = inner.headers.keys[0..inner.headers.len], .values = inner.headers.values[0..inner.headers.len], }, .arena = inner.arena, .connection_fd = inner.conn.stream.socket.handle, }; }};
fn mapMethod(m: httpz.Method) std.http.Method { return switch (m) { .GET => .GET, .HEAD => .HEAD, .POST => .POST, .PUT => .PUT, .PATCH => .PATCH, .DELETE => .DELETE, .OPTIONS => .OPTIONS, .CONNECT => .CONNECT, .OTHER => .GET, };}
pub fn parseMethod(raw: []const u8) std.http.Method { return std.meta.stringToEnum(std.http.Method, raw) orelse @fromBackingInt(@intCast(0));}
pub fn splitTarget(target: []const u8) struct { path: []const u8, query: ?[]const u8 } { if (std.mem.indexOfScalar(u8, target, '?')) |i| { return .{ .path = target[0..i], .query = target[i + 1 ..] }; } return .{ .path = target, .query = null };}
test "Headers.get is case-insensitive" { const keys: []const []const u8 = &.{ "content-type", "X-Foo" }; const values: []const []const u8 = &.{ "application/json", "bar" }; const h: Headers = .{ .keys = keys, .values = values };
try std.testing.expectEqualStrings("application/json", h.get("Content-Type").?); try std.testing.expectEqualStrings("bar", h.get("x-foo").?); try std.testing.expect(h.get("missing") == null);}
test "Request.queryParam parses pairs" { const req = Request{ .method = .GET, .target = "/csrf-token?client=abc&foo=bar", .path = "/csrf-token", .query = "client=abc&foo=bar", .body = "", .headers = .{ .keys = &.{}, .values = &.{} }, .arena = std.testing.allocator, }; try std.testing.expectEqualStrings("abc", req.queryParam("client").?); try std.testing.expectEqualStrings("bar", req.queryParam("foo").?); try std.testing.expect(req.queryParam("missing") == null);}
test "Request.parseJson decodes into a typed struct" { const Body = struct { name: []const u8, count: i32, active: bool, nickname: ?[]const u8 = null, };
var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit();
const req = Request{ .method = .POST, .target = "/x", .path = "/x", .query = null, .body = "{\"name\":\"hi\",\"count\":3,\"active\":true}", .headers = .{ .keys = &.{}, .values = &.{} }, .arena = arena.allocator(), }; const got = try req.parseJson(Body); try std.testing.expectEqualStrings("hi", got.name); try std.testing.expectEqual(@as(i32, 3), got.count); try std.testing.expectEqual(true, got.active); try std.testing.expect(got.nickname == null);}
test "Request.parseJson rejects unknown fields (matches ActionBaseModel extra=forbid)" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const req = Request{ .method = .POST, .target = "/x", .path = "/x", .query = null, // `deploymet_id` is a deliberate typo — strict mode catches it. .body = "{\"name\":\"hi\",\"deploymet_id\":\"oops\"}", .headers = .{ .keys = &.{}, .values = &.{} }, .arena = arena.allocator(), }; try std.testing.expectError(error.UnknownField, req.parseJson(struct { name: []const u8 }));}
test "Request.parseJson rejects malformed body" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const req = Request{ .method = .POST, .target = "/x", .path = "/x", .query = null, .body = "not-json", .headers = .{ .keys = &.{}, .values = &.{} }, .arena = arena.allocator(), }; try std.testing.expectError(error.SyntaxError, req.parseJson(struct { a: i32 }));}
test "Request.parseJsonValue gives an opaque tree" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const req = Request{ .method = .POST, .target = "/x", .path = "/x", .query = null, .body = "{\"k\":\"v\",\"n\":42}", .headers = .{ .keys = &.{}, .values = &.{} }, .arena = arena.allocator(), }; const v = try req.parseJsonValue(); try std.testing.expect(v == .object); try std.testing.expectEqualStrings("v", v.object.get("k").?.string);}
test "splitTarget separates path from query" { const r1 = splitTarget("/a/b?x=1"); try std.testing.expectEqualStrings("/a/b", r1.path); try std.testing.expectEqualStrings("x=1", r1.query.?);
const r2 = splitTarget("/a/b"); try std.testing.expectEqualStrings("/a/b", r2.path); try std.testing.expect(r2.query == null);}