//! wap.Server — runs httpz.Server(*App). The App dispatches HTTP via the //! host-provided `handler` and WS upgrades via the matching ws_route's //! factory + on_message + on_close. const std = @import("std"); const httpz = @import("httpz"); const request_mod = @import("request.zig"); const response_mod = @import("response.zig"); const ws_mod = @import("ws.zig"); const Allocator = std.mem.Allocator; const Io = std.Io; const log = std.log.scoped(.wap); pub const Handler = *const fn (req: *request_mod.Request, res: *response_mod.Response) anyerror!void; pub const Mount = struct { path: []const u8, handler: Handler, exact: bool = false, }; pub const DispatchOpts = struct { api_prefix: ?[]const u8 = null, not_found: ?Handler = null, }; pub fn dispatchMounts( req: *request_mod.Request, res: *response_mod.Response, mounts: []const Mount, opts: DispatchOpts, ) !void { if (try matchAndCall(req, res, req.path, mounts)) return; if (opts.api_prefix) |prefix| { if (std.mem.startsWith(u8, req.path, prefix) and req.path.len > prefix.len) { const stripped = req.path[prefix.len..]; if (try matchAndCall(req, res, stripped, mounts)) return; } } if (opts.not_found) |nf| return nf(req, res); _ = res.setStatus(.not_found).setHeader("content-type", "application/json"); try res.sendBody("{\"detail\":\"not found\"}"); } fn matchAndCall(req: *request_mod.Request, res: *response_mod.Response, target: []const u8, mounts: []const Mount) !bool { for (mounts) |m| { const hit = if (m.exact) std.mem.eql(u8, target, m.path) else std.mem.startsWith(u8, target, m.path); if (hit) { try m.handler(req, res); return true; } } return false; } pub const Config = struct { const prefect_event_max_size = 1_500_000; address: []const u8 = "127.0.0.1", port: u16 = 4200, handler: Handler, on_ready: ?*const fn ([]const u8, []const u8, u16) void = null, ready_label: []const u8 = "API", ws_routes: []const ws_mod.Route = &.{}, workers: u8 = 4, max_body_size: usize = 16 * 1024 * 1024, websocket_max_message_size: usize = prefect_event_max_size + 64, keepalive_timeout_seconds: u32 = 5, /// Retained for source compatibility; httpz applies its own timeout /// policy and these are now informational only. handshake_timeout_seconds: u32 = 5, handshake_max_size: u16 = 65535, handshake_max_headers: u16 = 128, }; /// httpz Handler type. Declares App.WebsocketHandler at the right scope so /// httpz's worker can upgrade WS connections without us having to register /// a separate-type per route. pub const App = struct { config: Config, io: Io, pub const WebsocketHandler = ws_mod.WsHandler; pub fn handle(self: *App, http_req: *httpz.Request, http_res: *httpz.Response) void { const upgraded = self.tryWsUpgrade(http_req, http_res) catch |err| blk: { log.err("ws upgrade error: {}", .{err}); http_res.setStatus(.internal_server_error); http_res.body = "ws upgrade failed"; break :blk true; }; if (upgraded) return; self.dispatchHttp(http_req, http_res) catch |err| { log.err("handler error: {} (method={s} path={s})", .{ err, @tagName(http_req.method), http_req.url.path }); http_res.setStatus(.internal_server_error); http_res.content_type = .JSON; http_res.body = "{\"detail\":\"internal error\"}"; }; } fn tryWsUpgrade(self: *App, http_req: *httpz.Request, http_res: *httpz.Response) !bool { // Cheap precheck: avoid running the route table on every HTTP // request. httpz expects `Upgrade: websocket` for the upgrade path. const upgrade = http_req.header("upgrade") orelse return false; if (!std.ascii.eqlIgnoreCase(upgrade, "websocket")) return false; const path = http_req.url.path; for (self.config.ws_routes) |*route| { const hit = switch (route.match) { .exact => std.mem.eql(u8, path, route.path), .prefix => std.mem.startsWith(u8, path, route.path), }; if (!hit) continue; // Only echo the route's declared subprotocol when the client // actually offered it (RFC 6455 §1.3). Compares token-by-token // against `Sec-WebSocket-Protocol`. const subprotocol_echo: ?[]const u8 = if (route.subprotocol) |declared| if (clientOfferedSubprotocol(http_req, declared)) declared else null else null; const ctx = ws_mod.Context{ .route = route, .allocator = std.heap.smp_allocator, .io = self.io, .handshake = .{ .url = path, .request = http_req }, .subprotocol = subprotocol_echo, }; return try httpz.upgradeWebsocket(WebsocketHandler, http_req, http_res, &ctx); } return false; } fn clientOfferedSubprotocol(http_req: *httpz.Request, name: []const u8) bool { const raw = http_req.header("sec-websocket-protocol") orelse return false; var it = std.mem.tokenizeAny(u8, raw, ", \t"); while (it.next()) |tok| { if (std.mem.eql(u8, tok, name)) return true; } return false; } fn dispatchHttp(self: *App, http_req: *httpz.Request, http_res: *httpz.Response) !void { var req = request_mod.Request.from(http_req); var res = response_mod.Response{ .inner = http_res, .arena = http_req.arena }; try self.config.handler(&req, &res); if (!res.is_sent) { log.warn("handler returned without writing response (method={s} path={s}); sending 204", .{ @tagName(http_req.method), http_req.url.path }); http_res.setStatus(.no_content); http_res.body = ""; } } }; pub const Server = struct { allocator: Allocator, io: Io, config: Config, app: App, inner: ?*httpz.Server(*App) = null, pub fn init(allocator: Allocator, io: Io, config: Config) !Server { return .{ .allocator = allocator, .io = io, .config = config, .app = .{ .config = config, .io = io }, }; } pub fn deinit(self: *Server) void { if (self.inner) |srv| { srv.deinit(); self.allocator.destroy(srv); self.inner = null; } } pub fn run(self: *Server) !void { const inner_ptr = try self.allocator.create(httpz.Server(*App)); errdefer self.allocator.destroy(inner_ptr); const ip = try std.Io.net.IpAddress.parse(self.config.address, self.config.port); inner_ptr.* = try httpz.Server(*App).init(self.io, self.allocator, .{ .address = .{ .ip = ip }, .request = .{ .max_body_size = self.config.max_body_size }, .timeout = .{ .keepalive = self.config.keepalive_timeout_seconds }, .workers = .{ .count = self.config.workers }, .websocket = .{ .max_message_size = self.config.websocket_max_message_size, .large_buffer_size = self.config.websocket_max_message_size, .large_buffer_pool = 2, }, }, &self.app); self.inner = inner_ptr; if (self.config.on_ready) |on_ready| { var listener = Listener{ .server = inner_ptr }; inner_ptr._mut.lockUncancelable(self.io); const thread = std.Thread.spawn(.{}, Listener.run, .{&listener}) catch |err| { inner_ptr._mut.unlock(self.io); return err; }; // Mirror httpz's listenInNewThread handshake, but retain startup errors // instead of letting an error-returning thread entry panic. while (inner_ptr._listener == null and !listener.finished) { inner_ptr._cond.waitUncancelable(self.io, &inner_ptr._mut); } const ready = inner_ptr._listener != null and !listener.finished; inner_ptr._mut.unlock(self.io); if (ready) on_ready(self.config.ready_label, self.config.address, self.config.port); thread.join(); if (listener.failure) |err| return err; } else { try inner_ptr.listen(); } } const Listener = struct { server: *httpz.Server(*App), failure: ?anyerror = null, finished: bool = false, fn run(self: *Listener) void { const failure: ?anyerror = if (self.server.listen()) |_| null else |err| err; self.server._mut.lockUncancelable(self.server.io); defer self.server._mut.unlock(self.server.io); self.failure = failure; self.finished = true; self.server._cond.signal(self.server.io); } }; pub fn stop(self: *Server) void { if (self.inner) |srv| srv.stop(); } };