gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/http1/http1.zig

161.9 KB

  1. // hl:http1 plugin — HTTP/1.1 server with epoll + I/O thread pool
  2. // Compiled to libhttp1.so, loaded by runtime via dlopen
  3. //
  4. // Architecture:
  5. // Acceptor thread (epoll on server fd) → PARK (epoll) → I/O thread pool (TLS + parse)
  6. // → request queue → Hybriel main thread
  7. //
  8. // An IDLE connection never occupies an I/O worker (mission 084). A worker's read() is
  9. // blocking, so a connection handed straight to the pool pins a thread until bytes arrive;
  10. // with the default `threads = 4`, four idle keep-alive sockets (one open browser tab is
  11. // already several) starved every later request. Instead every connection that is not
  12. // known to have readable bytes is PARKED in the parker thread's epoll, and only enters
  13. // conn_queue when it is actually readable (or hung up). See ParkedConns below.
  14. //
  15. // Exports:
  16. // hl_http1_create_server(port, host, cert_path, key_path, threads) → iterator of request objects
  17. // hl_http1_listen(port) → same with defaults (backward compat)
  18. //
  19. // Each request object: method, path, query (object), headers (object), body, respond (handle),
  20. // remoteAddress, bytes (the body as a Bytes, ticket #88), secure (TLS terminated here, #214)
  21. // Respond handle: call("send", status_code, body [, content_type]) → writes response
  22. const std = @import("std");
  23. const api = @import("plugin_api");
  24. const http = @import("http_common");
  25. const ws = @import("ws_common");
  26. // The outgoing WebSocket client's TLS (wss://, ticket #109) — the SAME client
  27. // half hl:fetch uses (system trust store, hostname verification on, an
  28. // optional extra `caFile` for a test fixture). Aliased away from `TlsContext`:
  29. // the name is taken below by http1's own pre-existing SERVER-only TLS type,
  30. // which this does not touch.
  31. const tls_client = @import("tls_common");
  32. const HlValue = api.HlValue;
  33. const HlObject = api.HlObject;
  34. const HlField = api.HlField;
  35. const HlIterator = api.HlIterator;
  36. const HlHandle = api.HlHandle;
  37. const HlString = api.HlString;
  38. const linux = std.os.linux;
  39. const posix = std.posix;
  40. const c = std.c;
  41. const PthreadMutex = c.pthread_mutex_t;
  42. const PthreadCond = c.pthread_cond_t;
  43. fn mutexInit(m: *PthreadMutex) void {
  44. // Static initializer is sufficient; explicit init not exposed in this std.c.
  45. _ = m;
  46. }
  47. fn mutexLock(m: *PthreadMutex) void {
  48. _ = c.pthread_mutex_lock(m);
  49. }
  50. fn mutexUnlock(m: *PthreadMutex) void {
  51. _ = c.pthread_mutex_unlock(m);
  52. }
  53. fn condInit(cnd: *PthreadCond) void {
  54. _ = cnd;
  55. }
  56. fn condSignal(cnd: *PthreadCond) void {
  57. _ = c.pthread_cond_signal(cnd);
  58. }
  59. fn condBroadcast(cnd: *PthreadCond) void {
  60. _ = c.pthread_cond_broadcast(cnd);
  61. }
  62. fn condWait(cnd: *PthreadCond, m: *PthreadMutex) void {
  63. _ = c.pthread_cond_wait(cnd, m);
  64. }
  65. // allocations cross the acceptor, I/O-worker and interpreter threads: the plugins'
  66. // allocator (plugin_api.zig), never the debug one, whose bookkeeping segfaulted in its
  67. // own free() under request churn (mission 027)
  68. const allocator = api.allocator;
  69. // Use direct syscall for stderr writes — std.debug.print uses std.Progress
  70. // which has ABI-incompatible global state when loaded as a plugin into a
  71. // binary compiled with a different Zig version.
  72. fn logMsg(msg: []const u8) void {
  73. _ = linux.write(2, msg.ptr, msg.len);
  74. }
  75. fn logFmt(comptime fmt: []const u8, args: anytype) void {
  76. var buf: [512]u8 = undefined;
  77. const s = std.fmt.bufPrint(&buf, fmt, args) catch return;
  78. logMsg(s);
  79. }
  80. // =========================================================================
  81. // SSE (Server-Sent Events) push channel — mission 031, ADDRESSED in 080
  82. // A registry of connected event-stream clients. `sse_start` (on the respond
  83. // handle) upgrades a GET request into a long-lived text/event-stream, assigns
  84. // the connection a stable id and registers it; `hl_http1_sse_broadcast` writes
  85. // a `data:` frame to every registered client and `hl_http1_sse_send` to ONE of
  86. // them, dropping any that error (peer closed). Touched only from the
  87. // interpreter (main) thread, but guarded by a mutex for safety.
  88. //
  89. // Mission 080 (D26): the id is a MONOTONIC counter, never the fd — a closed
  90. // connection's fd is recycled by the kernel within milliseconds, so an fd-keyed
  91. // push would eventually land on a stranger's socket. `sse_start` returns the id
  92. // (it used to return the raw fd, which no caller used), and the framework sends
  93. // it to the browser as the `__hlHello` event so the client can name itself.
  94. // =========================================================================
  95. // Mission 084: a subscription is reaped PROACTIVELY, not on the first failed push.
  96. // A closed tab used to stay in this registry until something happened to be pushed to
  97. // it — and because a scoped push (§9.5) sends nothing to a client whose needs did not
  98. // change, "something" could be never. Two mechanisms, both in the reaper thread:
  99. //
  100. // • EPOLLRDHUP on every registered fd — a closed tab sends FIN, which fires
  101. // immediately and costs no traffic at all. This is the primary detector.
  102. // • a periodic SSE COMMENT heartbeat (`:\n\n`, which EventSource ignores) — catches
  103. // a peer that vanished WITHOUT a FIN (killed machine, dropped NAT entry), which no
  104. // amount of epolling can see, and keeps intermediaries from timing the stream out.
  105. //
  106. // A heartbeat is also why one failed write is enough to declare death here: the probe
  107. // runs repeatedly, so the "first write after FIN succeeds, second gets EPIPE" TCP
  108. // behaviour just means the peer is reaped one tick later.
  109. const MSG_NOSIGNAL: u32 = 0x4000;
  110. const SseConn = struct { id: u32, fd: i32 };
  111. var sse_mutex: PthreadMutex = c.PTHREAD_MUTEX_INITIALIZER;
  112. var sse_subs: std.ArrayListUnmanaged(SseConn) = .empty;
  113. var sse_next_id: u32 = 1;
  114. /// how often the reaper writes its comment heartbeat / probes for silent death
  115. const SSE_HEARTBEAT_MS: i64 = 5_000;
  116. var sse_epoll_fd: i32 = -1;
  117. var sse_wake_fd: i32 = -1;
  118. var sse_reaper_thread: ?std.Thread = null;
  119. var sse_reaper_running = std.atomic.Value(bool).init(false);
  120. /// Start the reaper thread + its epoll. Idempotent; called under sse_mutex from the
  121. /// first sseRegister(), so a server that never opens a stream never spawns it.
  122. fn sseReaperEnsureLocked() void {
  123. if (sse_reaper_running.load(.acquire)) return;
  124. const ep_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  125. const ep: i32 = @bitCast(@as(u32, @truncate(ep_rc)));
  126. if (ep < 0) return;
  127. const ef_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  128. const ef: i32 = @bitCast(@as(u32, @truncate(ef_rc)));
  129. if (ef < 0) {
  130. _ = linux.close(ep);
  131. return;
  132. }
  133. var wake_ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = ef } };
  134. _ = linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, ef, &wake_ev);
  135. sse_epoll_fd = ep;
  136. sse_wake_fd = ef;
  137. sse_reaper_running.store(true, .release);
  138. sse_reaper_thread = std.Thread.spawn(.{}, sseReaperLoop, .{}) catch {
  139. sse_reaper_running.store(false, .release);
  140. _ = linux.close(ep);
  141. _ = linux.close(ef);
  142. sse_epoll_fd = -1;
  143. sse_wake_fd = -1;
  144. return;
  145. };
  146. }
  147. /// Drop subscription at index `i`: epoll DEL, close, remove. Caller holds sse_mutex.
  148. fn sseDropLocked(i: usize) void {
  149. const fd = sse_subs.items[i].fd;
  150. if (sse_epoll_fd >= 0) _ = linux.epoll_ctl(sse_epoll_fd, linux.EPOLL.CTL_DEL, fd, null);
  151. _ = linux.close(fd);
  152. _ = sse_subs.swapRemove(i);
  153. }
  154. /// The reaper: EPOLLRDHUP wakes it the instant a tab closes; the 1s timeout paces the
  155. /// heartbeat. Nothing here pushes application data, so a reap needs no traffic from the
  156. /// app at all — which is the whole point (mission 080's gap).
  157. fn sseReaperLoop() void {
  158. var events: [64]linux.epoll_event = undefined;
  159. var last_beat: i64 = monotonicMs();
  160. while (sse_reaper_running.load(.acquire)) {
  161. const n_rc = linux.epoll_wait(sse_epoll_fd, &events, events.len, 1000);
  162. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  163. if (n > 0) {
  164. for (events[0..@intCast(n)]) |ev| {
  165. if (ev.data.fd == sse_wake_fd) {
  166. var drain: u64 = 0;
  167. _ = linux.read(sse_wake_fd, @ptrCast(&drain), @sizeOf(u64));
  168. continue;
  169. }
  170. // A subscriber never SENDS on its stream, so any readable/hangup event
  171. // means the peer went away (or is misbehaving) — either way it is dead.
  172. mutexLock(&sse_mutex);
  173. for (sse_subs.items, 0..) |conn, i| {
  174. if (conn.fd == ev.data.fd) {
  175. sseDropLocked(i);
  176. break;
  177. }
  178. }
  179. mutexUnlock(&sse_mutex);
  180. }
  181. }
  182. const now = monotonicMs();
  183. if (now - last_beat >= SSE_HEARTBEAT_MS) {
  184. last_beat = now;
  185. mutexLock(&sse_mutex);
  186. var i: usize = 0;
  187. while (i < sse_subs.items.len) {
  188. // ":\n\n" is an SSE comment — EventSource ignores it, so this is a pure
  189. // liveness probe that never reaches an `onmessage` handler.
  190. if (!sseRawWrite(sse_subs.items[i].fd, ":\n\n")) {
  191. sseDropLocked(i);
  192. continue;
  193. }
  194. i += 1;
  195. }
  196. mutexUnlock(&sse_mutex);
  197. }
  198. }
  199. }
  200. // Write via sendto with MSG_NOSIGNAL so a dead peer yields EPIPE instead of
  201. // killing the process with SIGPIPE. Returns false on any short/failed write.
  202. fn sseRawWrite(fd: i32, data: []const u8) bool {
  203. var written: usize = 0;
  204. while (written < data.len) {
  205. const rc = linux.sendto(fd, data[written..].ptr, data.len - written, MSG_NOSIGNAL, null, 0);
  206. const n: isize = @bitCast(rc);
  207. if (n <= 0) return false;
  208. written += @intCast(n);
  209. }
  210. return true;
  211. }
  212. fn sseRegister(fd: i32) u32 {
  213. mutexLock(&sse_mutex);
  214. defer mutexUnlock(&sse_mutex);
  215. const id = sse_next_id;
  216. sse_next_id += 1;
  217. sse_subs.append(allocator, .{ .id = id, .fd = fd }) catch return 0;
  218. // Watch it for hangup from now on — see the reaper comment above.
  219. sseReaperEnsureLocked();
  220. if (sse_epoll_fd >= 0) {
  221. var ev = linux.epoll_event{
  222. .events = linux.EPOLL.RDHUP | linux.EPOLL.IN,
  223. .data = .{ .fd = fd },
  224. };
  225. _ = linux.epoll_ctl(sse_epoll_fd, linux.EPOLL.CTL_ADD, fd, &ev);
  226. }
  227. return id;
  228. }
  229. // One `data:` frame on one socket. Caller holds sse_mutex.
  230. fn sseWriteFrameLocked(fd: i32, msg: []const u8) bool {
  231. var ok = sseRawWrite(fd, "data: ");
  232. if (ok) ok = sseRawWrite(fd, msg);
  233. if (ok) ok = sseRawWrite(fd, "\n\n");
  234. return ok;
  235. }
  236. // Broadcast one SSE message to all subscribers. `msg` should be a single line
  237. // (callers send single-line JSON). Dead sockets are closed and removed.
  238. // Returns the number of clients successfully written to.
  239. fn sseBroadcast(msg: []const u8) usize {
  240. mutexLock(&sse_mutex);
  241. defer mutexUnlock(&sse_mutex);
  242. var count: usize = 0;
  243. var i: usize = 0;
  244. while (i < sse_subs.items.len) {
  245. if (!sseWriteFrameLocked(sse_subs.items[i].fd, msg)) {
  246. sseDropLocked(i);
  247. continue;
  248. }
  249. count += 1;
  250. i += 1;
  251. }
  252. return count;
  253. }
  254. // __native("http1.sse_count") → how many SSE subscriptions are currently LIVE.
  255. // The observable the proactive reaper exists to keep honest (mission 084): it must fall
  256. // when a client goes away, with nothing being pushed.
  257. export fn hl_http1_sse_count(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  258. _ = argc;
  259. _ = argv;
  260. mutexLock(&sse_mutex);
  261. defer mutexUnlock(&sse_mutex);
  262. return api.makeNumber(@floatFromInt(sse_subs.items.len));
  263. }
  264. // __native("http1.sse_alive", connId) → 1 if that subscription is still registered.
  265. // Lets the framework prune its own per-connection bookkeeping without pushing anything.
  266. export fn hl_http1_sse_alive(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  267. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  268. const id: u32 = @intFromFloat(argv[0].data.number);
  269. mutexLock(&sse_mutex);
  270. defer mutexUnlock(&sse_mutex);
  271. for (sse_subs.items) |conn| {
  272. if (conn.id == id) return api.makeNumber(1);
  273. }
  274. return api.makeNumber(0);
  275. }
  276. // __native("http1.sse_close", connId) → 1 closed / 0 gone.
  277. export fn hl_http1_sse_close(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  278. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  279. const id: u32 = @intFromFloat(argv[0].data.number);
  280. mutexLock(&sse_mutex);
  281. defer mutexUnlock(&sse_mutex);
  282. for (sse_subs.items, 0..) |conn, i| {
  283. if (conn.id == id) {
  284. sseDropLocked(i);
  285. return api.makeNumber(1);
  286. }
  287. }
  288. return api.makeNumber(0);
  289. }
  290. // __native("http1.sse_broadcast", jsonString) → number of clients pushed to.
  291. export fn hl_http1_sse_broadcast(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  292. if (argc < 1 or argv[0].type != .hl_string) return api.makeNumber(0);
  293. const msg = argv[0].data.string.ptr[0..argv[0].data.string.len];
  294. const n = sseBroadcast(msg);
  295. return api.makeNumber(@floatFromInt(n));
  296. }
  297. // __native("http1.sse_send", connId, jsonString) → 1 pushed / 0 gone.
  298. // Mission 080 (D26): the ADDRESSED half of the channel — the dependency-scoped
  299. // push sends a different payload to each client, so it cannot use broadcast.
  300. export fn hl_http1_sse_send(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  301. if (argc < 2 or argv[0].type != .hl_number or argv[1].type != .hl_string) return api.makeNumber(0);
  302. const id: u32 = @intFromFloat(argv[0].data.number);
  303. const msg = argv[1].data.string.ptr[0..argv[1].data.string.len];
  304. mutexLock(&sse_mutex);
  305. defer mutexUnlock(&sse_mutex);
  306. for (sse_subs.items, 0..) |conn, i| {
  307. if (conn.id != id) continue;
  308. if (!sseWriteFrameLocked(conn.fd, msg)) {
  309. sseDropLocked(i);
  310. return api.makeNumber(0);
  311. }
  312. return api.makeNumber(1);
  313. }
  314. return api.makeNumber(0);
  315. }
  316. // =========================================================================
  317. // WebSocket engine (mission 064, decisions D8/D9)
  318. //
  319. // Framing lives in the shared core (plugins/http/ws_common.zig); this engine
  320. // owns the h1-specific parts: the Upgrade/101 handshake (done inline in the
  321. // I/O worker, see readAndParseRequest) and the socket lifecycle after it.
  322. //
  323. // One engine per listening server: each owns a queue, peers and a reader
  324. // thread that epolls its upgraded sockets with level-triggered EPOLLIN only —
  325. // EPOLLOUT is never armed, so an idle connection never wakes the loop (the
  326. // busy-spin trap found in the http2 TLS path). Complete messages become
  327. // WsEvent entries that the interpreter drains via the hl_http1_ws_events
  328. // iterator (registered on the event loop like the request iterator).
  329. //
  330. // Outbound writes (send/broadcast/ping/close + pong replies) happen under
  331. // ws_mutex from either the interpreter thread or the reader thread. Sockets
  332. // are non-blocking; a slow consumer gets bounded EAGAIN retries (~100ms)
  333. // and is dropped rather than buffered (no outbound queue, no EPOLLOUT).
  334. // WS upgrades are plain-HTTP only for now (TLS WS = future work, like SSE).
  335. // =========================================================================
  336. const WsEventKind = enum(u8) { connect, message, close, pong };
  337. const WsEvent = struct {
  338. kind: WsEventKind,
  339. id: u32,
  340. data: ?[]u8 = null, // allocated payload (message data / close reason)
  341. is_binary: bool = false,
  342. code: u16 = 0, // close code
  343. // Mission 093: the UPGRADE REQUEST's `Cookie` header, verbatim, carried on the
  344. // `connect` event only. A WebSocket handshake is an ordinary HTTP request, so
  345. // the browser sends the session cookie with it automatically — this is the one
  346. // moment the socket can be attributed to whoever loaded the page, and after the
  347. // 101 the request (and its headers) is freed. Allocated; freed with the event.
  348. cookie: ?[]u8 = null,
  349. path: ?[]u8 = null, // raw upgrade request target, including query (#353)
  350. // Ticket #74: the upgrade request's `Host` header, verbatim, on `connect` only —
  351. // the address the browser dialled, which a page served per subdomain is rendered
  352. // for. Allocated; freed with the event.
  353. host: ?[]u8 = null,
  354. // Ticket #105: EVERY header of the upgrade request, `name: value` lines joined by
  355. // `\n` (names already lowercase), on `connect` only — what a page constructed for
  356. // a navigation over this socket reads as `headers`. Allocated; freed with the event.
  357. headers: ?[]u8 = null,
  358. // Ticket #214: the peer's address ("a.b.c.d", the request's `remoteAddress` form) on
  359. // `connect` only — null when the kernel cannot say. Allocated; freed with the event.
  360. ip: ?[]u8 = null,
  361. // Ticket #214: whether the upgrade arrived over TLS this server terminated. Upgrades
  362. // are plain-HTTP only today (a TLS connection is never upgraded), so always false.
  363. secure: bool = false,
  364. stamp: u64 = 0, // api.stamp() when queued (wsQueue)
  365. };
  366. /// Queue one server-side event, stamped (plugin_api.zig `head_stamp_fn`). Caller holds `engine.ws_mutex`.
  367. fn wsQueue(engine: *WsEngine, ev: WsEvent) !void {
  368. var e = ev;
  369. e.stamp = api.stamp();
  370. try engine.ws_event_queue.append(allocator, e);
  371. // Also covers close events queued by failed sends outside the reader.
  372. http.ringWake(engine.ws_loop_wake_fd);
  373. }
  374. /// `head_stamp_fn` of the server's event source: when its next event was queued.
  375. fn wsEventsHeadStamp(ctx: ?*anyopaque) callconv(.c) u64 {
  376. const engine: *WsEngine = @ptrCast(@alignCast(ctx orelse return api.STAMP_NONE));
  377. mutexLock(&engine.ws_mutex);
  378. defer mutexUnlock(&engine.ws_mutex);
  379. return if (engine.ws_event_queue.items.len == 0) api.STAMP_NONE else engine.ws_event_queue.items[0].stamp;
  380. }
  381. const WsClient = struct {
  382. id: u32,
  383. fd: i32,
  384. decoder: ws.Decoder,
  385. closing: bool = false, // server sent close, awaiting peer echo
  386. // liveness (mission 091): when this socket last produced a frame, and when
  387. // the sweep's ping went out (0 = none outstanding). A TCP connection whose
  388. // peer vanished without a FIN stays writable indefinitely, so "still open"
  389. // is not evidence of a live peer — the pong is.
  390. last_seen_ms: i64 = 0,
  391. ping_at_ms: i64 = 0,
  392. };
  393. const WsEngine = struct {
  394. ws_mutex: PthreadMutex = c.PTHREAD_MUTEX_INITIALIZER,
  395. ws_clients: std.ArrayListUnmanaged(*WsClient) = .empty,
  396. ws_event_queue: std.ArrayListUnmanaged(WsEvent) = .empty,
  397. ws_epoll_fd: i32 = -1,
  398. ws_wake_fd: i32 = -1,
  399. // Kept alive with the core: an event loop may still hold this fd.
  400. ws_loop_wake_fd: i32 = -1,
  401. ws_thread: ?std.Thread = null,
  402. ws_running: std.atomic.Value(bool) = .init(false),
  403. ws_enabled: std.atomic.Value(bool) = .init(false),
  404. ws_ping_ms: i64 = WS_PING_MS_DEFAULT,
  405. ws_pong_ms: i64 = WS_PONG_MS_DEFAULT,
  406. };
  407. // Connection IDs stay process-unique so the existing WsClient API is unchanged.
  408. var ws_next_id = std.atomic.Value(u32).init(1);
  409. // --- liveness sweep (mission 091) ----------------------------------------
  410. // The reader thread already wakes every 500ms (the epoll timeout), so the sweep
  411. // costs no timer and no new thread: on every tick it pings sockets that have
  412. // gone quiet and drops the ones whose pong is overdue. The drop enqueues the
  413. // ordinary `close` event, so every consumer above (hl:web's subscription
  414. // registry included) prunes through the path it already had — nothing upstream
  415. // learns a new concept, and nothing at the hl level needs a timer.
  416. //
  417. // Operator knobs, read once at engine start; the defaults are production
  418. // values, the tests shrink them.
  419. const WS_PING_MS_DEFAULT: i64 = 15000; // quiet this long -> ask
  420. const WS_PONG_MS_DEFAULT: i64 = 10000; // no answer in this long -> gone
  421. /// MONOTONIC milliseconds — a timeout measured against the wall clock would fire
  422. /// early or never after an NTP step.
  423. fn wsNowMs() i64 {
  424. var ts: linux.timespec = undefined;
  425. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  426. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  427. }
  428. fn wsEnvMs(name: [:0]const u8, fallback: i64) i64 {
  429. const raw = std.mem.span(std.c.getenv(name) orelse return fallback);
  430. const n = std.fmt.parseInt(i64, std.mem.trim(u8, raw, " \t"), 10) catch return fallback;
  431. if (n <= 0) return fallback;
  432. return n;
  433. }
  434. const EAGAIN_ERR: isize = 11;
  435. const EINTR_ERR: isize = 4;
  436. /// WriteFn callback over a raw fd (context = fd stuffed into the pointer).
  437. /// Non-blocking socket: bounded EAGAIN retries, then give up (caller drops).
  438. fn wsFdWrite(ctx: ?*anyopaque, data: []const u8) bool {
  439. const fd: i32 = @intCast(@intFromPtr(ctx));
  440. var written: usize = 0;
  441. var retries: u32 = 0;
  442. while (written < data.len) {
  443. const rc = linux.sendto(fd, data[written..].ptr, data.len - written, MSG_NOSIGNAL, null, 0);
  444. const n: isize = @bitCast(rc);
  445. if (n > 0) {
  446. written += @intCast(n);
  447. retries = 0;
  448. continue;
  449. }
  450. const e = -n;
  451. if (e == EAGAIN_ERR) {
  452. retries += 1;
  453. if (retries > 100) return false; // ~100ms of backpressure → drop
  454. const req = linux.timespec{ .sec = 0, .nsec = 1_000_000 }; // 1ms
  455. _ = linux.nanosleep(&req, null);
  456. continue;
  457. }
  458. if (e == EINTR_ERR) continue;
  459. return false;
  460. }
  461. return true;
  462. }
  463. fn wsFdCtx(fd: i32) ?*anyopaque {
  464. return @ptrFromInt(@as(usize, @intCast(fd)));
  465. }
  466. /// Start the reader thread + epoll instance. Idempotent. Called from the
  467. /// interpreter thread (hl_http1_ws_events); also flips engine.ws_enabled so the I/O
  468. /// workers start honoring Upgrade requests.
  469. fn wsEnsureStarted(engine: *WsEngine) bool {
  470. mutexLock(&engine.ws_mutex);
  471. defer mutexUnlock(&engine.ws_mutex);
  472. if (engine.ws_running.load(.acquire)) return true;
  473. engine.ws_ping_ms = wsEnvMs("HL_WS_PING_MS", WS_PING_MS_DEFAULT);
  474. engine.ws_pong_ms = wsEnvMs("HL_WS_PONG_TIMEOUT_MS", WS_PONG_MS_DEFAULT);
  475. const ep_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  476. const ep: i32 = @bitCast(@as(u32, @truncate(ep_rc)));
  477. if (ep < 0) return false;
  478. const ef_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  479. const ef: i32 = @bitCast(@as(u32, @truncate(ef_rc)));
  480. if (ef < 0) {
  481. _ = linux.close(ep);
  482. return false;
  483. }
  484. var wake_ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = ef } };
  485. _ = linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, ef, &wake_ev);
  486. engine.ws_epoll_fd = ep;
  487. engine.ws_wake_fd = ef;
  488. if (engine.ws_loop_wake_fd < 0) engine.ws_loop_wake_fd = http.makeWakeFd(); // mission 256
  489. engine.ws_running.store(true, .release);
  490. engine.ws_thread = std.Thread.spawn(.{}, wsReaderLoop, .{engine}) catch {
  491. engine.ws_running.store(false, .release);
  492. _ = linux.close(ep);
  493. _ = linux.close(ef);
  494. engine.ws_epoll_fd = -1;
  495. engine.ws_wake_fd = -1;
  496. return false;
  497. };
  498. engine.ws_enabled.store(true, .release);
  499. return true;
  500. }
  501. fn wsWake(engine: *WsEngine) void {
  502. if (engine.ws_wake_fd >= 0) {
  503. const one: u64 = 1;
  504. _ = linux.write(engine.ws_wake_fd, @ptrCast(&one), @sizeOf(u64));
  505. }
  506. }
  507. /// The upgrade's headers as `name: value` lines joined by `\n` (ticket #105) — one
  508. /// allocation the connect event carries; a parsed header holds no `\n`. Null when
  509. /// there are none or the allocation fails (the connection still opens).
  510. fn joinHeaders(items: []const HeaderPair) ?[]u8 {
  511. var len: usize = 0;
  512. for (items) |hdr| len += hdr.key.len + 2 + hdr.value.len + 1;
  513. if (len == 0) return null;
  514. const out = allocator.alloc(u8, len - 1) catch return null;
  515. var at: usize = 0;
  516. for (items, 0..) |hdr, i| {
  517. if (i > 0) {
  518. out[at] = '\n';
  519. at += 1;
  520. }
  521. @memcpy(out[at .. at + hdr.key.len], hdr.key);
  522. at += hdr.key.len;
  523. @memcpy(out[at .. at + 2], ": ");
  524. at += 2;
  525. @memcpy(out[at .. at + hdr.value.len], hdr.value);
  526. at += hdr.value.len;
  527. }
  528. return out;
  529. }
  530. /// Hand an upgraded socket to the engine. Called from an I/O worker thread
  531. /// right after the 101 was written. `leftover` = bytes the client sent after
  532. /// the handshake that were already consumed into the header buffer. `cookie` is
  533. /// the handshake's `Cookie` header (mission 093) — copied here, because the
  534. /// parsed request is freed the moment this returns. `host` is its `Host` header
  535. /// (ticket #74), copied for the same reason. `headers` is all of them as
  536. /// `name: value` lines (ticket #105), already an allocated copy: owned from here.
  537. /// `handshake` is the 101 response. It is written HERE, under `engine.ws_mutex` and after the
  538. /// `connect` event is queued (ticket: 039_http1_ws_client, 2026-10-02): written before
  539. /// registering, an in-process client could read it and queue its `open` ahead of the
  540. /// server's `connect`, and a `peer.send` from `on connect` could not overtake it either.
  541. /// The peer address of a connected socket as "a.b.c.d" (IPv4 listener), allocated; null
  542. /// when the kernel cannot say.
  543. fn peerIpText(fd: i32) ?[]u8 {
  544. var peer: linux.sockaddr.in = undefined;
  545. var peer_len: u32 = @sizeOf(linux.sockaddr.in);
  546. const rc = linux.getpeername(fd, @ptrCast(&peer), &peer_len);
  547. if (@as(isize, @bitCast(rc)) != 0 or peer.family != linux.AF.INET) return null;
  548. const a: [4]u8 = @bitCast(peer.addr);
  549. return std.fmt.allocPrint(allocator, "{d}.{d}.{d}.{d}", .{ a[0], a[1], a[2], a[3] }) catch null;
  550. }
  551. fn wsRegisterClient(engine: *WsEngine, fd: i32, handshake: []const u8, leftover: []const u8, cookie: []const u8, host: []const u8, headers: ?[]u8, path: []const u8) void {
  552. // Non-blocking for the reader loop
  553. const flags_rc = linux.fcntl(fd, linux.F.GETFL, @as(usize, 0));
  554. const flags_i: isize = @bitCast(flags_rc);
  555. if (flags_i >= 0) {
  556. var oflags: linux.O = @bitCast(@as(u32, @truncate(flags_rc)));
  557. oflags.NONBLOCK = true;
  558. _ = linux.fcntl(fd, linux.F.SETFL, @as(usize, @as(u32, @bitCast(oflags))));
  559. }
  560. mutexLock(&engine.ws_mutex);
  561. const client = allocator.create(WsClient) catch {
  562. mutexUnlock(&engine.ws_mutex);
  563. if (headers) |hd| allocator.free(hd);
  564. _ = linux.close(fd);
  565. return;
  566. };
  567. client.* = .{
  568. .id = ws_next_id.fetchAdd(1, .monotonic),
  569. .fd = fd,
  570. .decoder = ws.Decoder.init(allocator),
  571. .last_seen_ms = wsNowMs(),
  572. };
  573. engine.ws_clients.append(allocator, client) catch {
  574. allocator.destroy(client);
  575. mutexUnlock(&engine.ws_mutex);
  576. if (headers) |hd| allocator.free(hd);
  577. _ = linux.close(fd);
  578. return;
  579. };
  580. const cookie_copy: ?[]u8 = if (cookie.len > 0) (allocator.dupe(u8, cookie) catch null) else null;
  581. const host_copy: ?[]u8 = if (host.len > 0) (allocator.dupe(u8, host) catch null) else null;
  582. const path_copy = allocator.dupe(u8, path) catch null;
  583. const ip_copy = peerIpText(fd);
  584. wsQueue(engine, .{ .kind = .connect, .id = client.id, .cookie = cookie_copy, .host = host_copy, .headers = headers, .path = path_copy, .ip = ip_copy, .secure = false }) catch {
  585. if (path_copy) |pc| allocator.free(pc);
  586. if (ip_copy) |ic| allocator.free(ic);
  587. if (cookie_copy) |cc| allocator.free(cc);
  588. if (host_copy) |hc| allocator.free(hc);
  589. if (headers) |hd| allocator.free(hd);
  590. };
  591. if (leftover.len > 0) client.decoder.feed(leftover) catch {};
  592. if (!wsFdWrite(wsFdCtx(fd), handshake)) {
  593. // the same answer a failed send gets: `close` 1006 after the `connect`
  594. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  595. wsRemoveLocked(engine, engine.ws_clients.items.len - 1);
  596. mutexUnlock(&engine.ws_mutex);
  597. return;
  598. }
  599. mutexUnlock(&engine.ws_mutex);
  600. // Level-triggered EPOLLIN only (never EPOLLOUT): pending socket data fires
  601. // immediately, idle connections cost nothing.
  602. var ev = linux.epoll_event{ .events = linux.EPOLL.IN | linux.EPOLL.RDHUP, .data = .{ .fd = fd } };
  603. _ = linux.epoll_ctl(engine.ws_epoll_fd, linux.EPOLL.CTL_ADD, fd, &ev);
  604. if (leftover.len > 0) wsWake(engine); // decoder-buffered bytes won't fire EPOLLIN
  605. // This runs on an I/O WORKER thread, not the reader thread, and it queued a
  606. // `connect` — so it rings the event loop itself (mission 256).
  607. http.ringWake(engine.ws_loop_wake_fd);
  608. }
  609. fn wsFindByFdLocked(engine: *WsEngine, fd: i32) ?usize {
  610. for (engine.ws_clients.items, 0..) |cl, i| {
  611. if (cl.fd == fd) return i;
  612. }
  613. return null;
  614. }
  615. fn wsFindByIdLocked(engine: *WsEngine, id: u32) ?usize {
  616. for (engine.ws_clients.items, 0..) |cl, i| {
  617. if (cl.id == id) return i;
  618. }
  619. return null;
  620. }
  621. /// Remove client at index: epoll DEL, close fd, free state. Mutex held.
  622. fn wsRemoveLocked(engine: *WsEngine, idx: usize) void {
  623. const client = engine.ws_clients.items[idx];
  624. _ = linux.epoll_ctl(engine.ws_epoll_fd, linux.EPOLL.CTL_DEL, client.fd, null);
  625. _ = linux.close(client.fd);
  626. client.decoder.deinit();
  627. _ = engine.ws_clients.swapRemove(idx);
  628. allocator.destroy(client);
  629. }
  630. /// Drain the client's decoder; enqueue events, auto-reply pings, run the
  631. /// close handshake. Returns true if the client was removed. Mutex held.
  632. fn wsDrainDecoderLocked(engine: *WsEngine, idx: usize) bool {
  633. const client = engine.ws_clients.items[idx];
  634. while (true) {
  635. const maybe_ev = client.decoder.next() catch {
  636. // OOM mid-decode — drop the connection
  637. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1011 }) catch {};
  638. wsRemoveLocked(engine, idx);
  639. return true;
  640. };
  641. const ev = maybe_ev orelse return false;
  642. // Any complete frame is proof of life, and it answers an outstanding
  643. // sweep ping whatever its opcode — a peer that is talking is not dead.
  644. client.last_seen_ms = wsNowMs();
  645. client.ping_at_ms = 0;
  646. switch (ev) {
  647. .text => |p| wsQueue(engine, .{ .kind = .message, .id = client.id, .data = p }) catch allocator.free(p),
  648. .binary => |p| wsQueue(engine, .{ .kind = .message, .id = client.id, .data = p, .is_binary = true }) catch allocator.free(p),
  649. .ping => |p| {
  650. _ = ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .pong, p);
  651. allocator.free(p);
  652. },
  653. .pong => |p| {
  654. allocator.free(p);
  655. wsQueue(engine, .{ .kind = .pong, .id = client.id }) catch {};
  656. },
  657. // QUEUED BEFORE THE ANSWER IS WRITTEN, as the 101 is: the peer may be a
  658. // client in this process, whose `close` the echo causes, and the loop
  659. // delivers in stamp order (plugin_api.zig `head_stamp_fn`)
  660. .close => |cl| {
  661. const code = cl.code;
  662. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = code, .data = cl.reason }) catch allocator.free(cl.reason);
  663. if (!client.closing) {
  664. const echo_code = if (code == ws.CLOSE_NO_STATUS) ws.CLOSE_NORMAL else code;
  665. _ = ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), echo_code, "");
  666. }
  667. wsRemoveLocked(engine, idx);
  668. return true;
  669. },
  670. .protocol_error => |code| {
  671. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = code }) catch {};
  672. _ = ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), code, "");
  673. wsRemoveLocked(engine, idx);
  674. return true;
  675. },
  676. }
  677. }
  678. }
  679. /// Read all available bytes from the client socket into its decoder, then
  680. /// drain. Returns true if the client was removed. Mutex held.
  681. fn wsServiceClientLocked(engine: *WsEngine, idx: usize) bool {
  682. const client = engine.ws_clients.items[idx];
  683. var buf: [16384]u8 = undefined;
  684. while (true) {
  685. const rc = linux.read(client.fd, &buf, buf.len);
  686. const n: isize = @bitCast(rc);
  687. if (n > 0) {
  688. client.decoder.feed(buf[0..@intCast(n)]) catch {};
  689. continue;
  690. }
  691. if (n == 0) {
  692. // Peer closed without a close frame → 1006 abnormal closure
  693. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  694. wsRemoveLocked(engine, idx);
  695. return true;
  696. }
  697. const e = -n;
  698. if (e == EINTR_ERR) continue;
  699. if (e == EAGAIN_ERR) break; // all available data consumed
  700. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  701. wsRemoveLocked(engine, idx);
  702. return true;
  703. }
  704. return wsDrainDecoderLocked(engine, idx);
  705. }
  706. /// One liveness pass over every upgraded socket. Quiet for longer than
  707. /// engine.ws_ping_ms → send a protocol ping (RFC 6455 §5.5.2; every browser answers it
  708. /// at the protocol layer, so nothing application-side is involved). A ping that
  709. /// stands unanswered for engine.ws_pong_ms → the peer is gone however open the socket
  710. /// looks: enqueue the SAME `close` event a real FIN would have produced and drop
  711. /// the connection. That is the whole mechanism — no separate timer, no new
  712. /// thread, no concept added above this file.
  713. fn wsSweep(engine: *WsEngine) void {
  714. const now = wsNowMs();
  715. mutexLock(&engine.ws_mutex);
  716. defer mutexUnlock(&engine.ws_mutex);
  717. var i: usize = 0;
  718. while (i < engine.ws_clients.items.len) {
  719. const client = engine.ws_clients.items[i];
  720. if (client.ping_at_ms != 0) {
  721. if (now - client.ping_at_ms > engine.ws_pong_ms) {
  722. wsQueue(engine, .{
  723. .kind = .close,
  724. .id = client.id,
  725. .code = ws.CLOSE_GOING_AWAY,
  726. }) catch {};
  727. wsRemoveLocked(engine, i);
  728. continue;
  729. }
  730. } else if (now - client.last_seen_ms > engine.ws_ping_ms) {
  731. if (ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .ping, "")) {
  732. client.ping_at_ms = now;
  733. } else {
  734. // the write itself failed — this one needs no grace period
  735. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  736. wsRemoveLocked(engine, i);
  737. continue;
  738. }
  739. }
  740. i += 1;
  741. }
  742. }
  743. fn wsReaderLoop(engine: *WsEngine) void {
  744. var events: [64]linux.epoll_event = undefined;
  745. while (engine.ws_running.load(.acquire)) {
  746. const n_rc = linux.epoll_wait(engine.ws_epoll_fd, &events, events.len, 500);
  747. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  748. // The 500ms epoll timeout IS the sweep's clock: an idle loop still ticks,
  749. // and a busy one sweeps just as often because the check is on wall time.
  750. if (n <= 0) {
  751. wsSweep(engine);
  752. continue;
  753. }
  754. for (events[0..@intCast(n)]) |ev| {
  755. if (ev.data.fd == engine.ws_wake_fd) {
  756. var drain: u64 = 0;
  757. _ = linux.read(engine.ws_wake_fd, @ptrCast(&drain), @sizeOf(u64));
  758. if (!engine.ws_running.load(.acquire)) return;
  759. // Drain decoder-buffered data (e.g. handshake leftover)
  760. mutexLock(&engine.ws_mutex);
  761. var i: usize = 0;
  762. while (i < engine.ws_clients.items.len) {
  763. if (!wsDrainDecoderLocked(engine, i)) i += 1;
  764. }
  765. mutexUnlock(&engine.ws_mutex);
  766. continue;
  767. }
  768. mutexLock(&engine.ws_mutex);
  769. if (wsFindByFdLocked(engine, ev.data.fd)) |idx| {
  770. _ = wsServiceClientLocked(engine, idx);
  771. }
  772. mutexUnlock(&engine.ws_mutex);
  773. }
  774. wsSweep(engine);
  775. }
  776. }
  777. /// Stop the engine: join the reader thread, close all sockets, free queues.
  778. /// Runs after this server's I/O workers have joined, before the runtime
  779. /// dlcloses this .so, so neither upgrades nor readers outlive the engine.
  780. fn wsShutdown(engine: *WsEngine) void {
  781. if (!engine.ws_running.swap(false, .acq_rel)) return;
  782. wsWake(engine);
  783. if (engine.ws_thread) |t| {
  784. t.join();
  785. engine.ws_thread = null;
  786. }
  787. mutexLock(&engine.ws_mutex);
  788. for (engine.ws_clients.items) |client| {
  789. _ = ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), ws.CLOSE_GOING_AWAY, "");
  790. _ = linux.close(client.fd);
  791. client.decoder.deinit();
  792. allocator.destroy(client);
  793. }
  794. engine.ws_clients.deinit(allocator);
  795. engine.ws_clients = .empty;
  796. for (engine.ws_event_queue.items) |*ev| {
  797. if (ev.data) |d| allocator.free(d);
  798. if (ev.cookie) |ck| allocator.free(ck);
  799. if (ev.path) |pc| allocator.free(pc);
  800. if (ev.host) |hc| allocator.free(hc);
  801. if (ev.headers) |hd| allocator.free(hd);
  802. if (ev.ip) |ip| allocator.free(ip);
  803. }
  804. engine.ws_event_queue.deinit(allocator);
  805. engine.ws_event_queue = .empty;
  806. mutexUnlock(&engine.ws_mutex);
  807. if (engine.ws_epoll_fd >= 0) _ = linux.close(engine.ws_epoll_fd);
  808. if (engine.ws_wake_fd >= 0) _ = linux.close(engine.ws_wake_fd);
  809. engine.ws_epoll_fd = -1;
  810. engine.ws_wake_fd = -1;
  811. // `engine.ws_loop_wake_fd` is deliberately NOT closed: the event loop may still hold
  812. // it in its epoll set, and a closed fd number gets REUSED — the loop would
  813. // then be watching whatever opened next. One eventfd per engine, kept for
  814. // the process's life (mission 256).
  815. engine.ws_enabled.store(false, .release);
  816. }
  817. // --- Interpreter-facing exports ------------------------------------------
  818. const ws_kind_names = [_][]const u8{ "connect", "message", "close", "pong" };
  819. fn wsEventObjDeinit(obj: *HlObject) callconv(.c) void {
  820. // fields[2] is "data", fields[5] "cookie", fields[6] "host" and fields[7]
  821. // "headers" — allocated iff non-empty (empty = the static "").
  822. const s = obj.fields[2].value.data.string;
  823. if (s.len > 0) allocator.free(s.ptr[0..s.len]);
  824. const ck = obj.fields[5].value.data.string;
  825. if (ck.len > 0) allocator.free(ck.ptr[0..ck.len]);
  826. const hs = obj.fields[6].value.data.string;
  827. if (hs.len > 0) allocator.free(hs.ptr[0..hs.len]);
  828. const hd = obj.fields[7].value.data.string;
  829. if (hd.len > 0) allocator.free(hd.ptr[0..hd.len]);
  830. const ipv = obj.fields[8].value.data.string; // "ip", allocated iff non-empty
  831. if (ipv.len > 0) allocator.free(ipv.ptr[0..ipv.len]);
  832. const path = obj.fields[10].value.data.string;
  833. if (path.len > 0) allocator.free(path.ptr[0..path.len]);
  834. allocator.free(obj.fields[0..obj.field_count]);
  835. allocator.destroy(obj);
  836. }
  837. /// try_next over the WS event queue → { kind, id, data, binary, code, cookie, host, headers }
  838. /// or null. `cookie` is the handshake's Cookie header, `host` its Host header and
  839. /// `headers` all of its headers as `name: value` lines, each non-empty only on
  840. /// `connect` (mission 093, tickets #74 and #105).
  841. fn wsEventsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  842. const engine: *WsEngine = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  843. mutexLock(&engine.ws_mutex);
  844. if (engine.ws_event_queue.items.len == 0) {
  845. mutexUnlock(&engine.ws_mutex);
  846. return api.makeNull();
  847. }
  848. const ev = engine.ws_event_queue.orderedRemove(0);
  849. if (engine.ws_event_queue.items.len > 0) http.ringWake(engine.ws_loop_wake_fd);
  850. mutexUnlock(&engine.ws_mutex);
  851. const fields = allocator.alloc(HlField, 11) catch {
  852. if (ev.ip) |ic| allocator.free(ic);
  853. if (ev.data) |d| allocator.free(d);
  854. if (ev.cookie) |ck| allocator.free(ck);
  855. if (ev.path) |pc| allocator.free(pc);
  856. if (ev.host) |hc| allocator.free(hc);
  857. if (ev.headers) |hd| allocator.free(hd);
  858. return api.makeNull();
  859. };
  860. const data_slice: []const u8 = if (ev.data) |d| d else "";
  861. const cookie_slice: []const u8 = if (ev.cookie) |ck| ck else "";
  862. const host_slice: []const u8 = if (ev.host) |hc| hc else "";
  863. const headers_slice: []const u8 = if (ev.headers) |hd| hd else "";
  864. fields[0] = .{ .key = http.hlStr("kind"), .value = api.makeString(ws_kind_names[@intFromEnum(ev.kind)]) };
  865. fields[1] = .{ .key = http.hlStr("id"), .value = api.makeNumber(@floatFromInt(ev.id)) };
  866. fields[2] = .{ .key = http.hlStr("data"), .value = api.makeString(data_slice) };
  867. fields[3] = .{ .key = http.hlStr("binary"), .value = api.makeBool(ev.is_binary) };
  868. fields[4] = .{ .key = http.hlStr("code"), .value = api.makeNumber(@floatFromInt(ev.code)) };
  869. fields[5] = .{ .key = http.hlStr("cookie"), .value = api.makeString(cookie_slice) };
  870. fields[6] = .{ .key = http.hlStr("host"), .value = api.makeString(host_slice) };
  871. fields[7] = .{ .key = http.hlStr("headers"), .value = api.makeString(headers_slice) };
  872. fields[8] = .{ .key = http.hlStr("ip"), .value = api.makeString(if (ev.ip) |ic| ic else "") };
  873. fields[9] = .{ .key = http.hlStr("secure"), .value = api.makeBool(ev.secure) };
  874. fields[10] = .{ .key = http.hlStr("path"), .value = api.makeString(if (ev.path) |pc| pc else "") };
  875. const obj = allocator.create(HlObject) catch {
  876. if (ev.data) |d| allocator.free(d);
  877. if (ev.cookie) |ck| allocator.free(ck);
  878. if (ev.path) |pc| allocator.free(pc);
  879. if (ev.host) |hc| allocator.free(hc);
  880. if (ev.headers) |hd| allocator.free(hd);
  881. if (ev.ip) |ic| allocator.free(ic);
  882. allocator.free(fields);
  883. return api.makeNull();
  884. };
  885. obj.* = .{ .fields = fields.ptr, .field_count = 11, .deinit_fn = &wsEventObjDeinit };
  886. return api.makeObject(obj);
  887. }
  888. fn wsEventsIterDeinit(_: ?*anyopaque) callconv(.c) void {
  889. // The request iterator owns shutdown: join I/O workers before the WS reader.
  890. // The small engine allocation and its loop wake fd outlive either iterator,
  891. // whose retirement order is unspecified (as for an explicitly closed core).
  892. }
  893. /// __native("http1.ws_events", port) → this listener's event iterator.
  894. export fn hl_http1_ws_events(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  895. const engine = wsEngineForPort(argc, argv, 0) orelse return api.makeNull();
  896. if (!wsEnsureStarted(engine)) return api.makeNull();
  897. const iter = allocator.create(HlIterator) catch return api.makeNull();
  898. iter.* = .{
  899. .context = engine,
  900. .next_fn = &wsEventsTryNext, // non-blocking either way — event loop only
  901. .deinit_fn = &wsEventsIterDeinit,
  902. .try_next_fn = &wsEventsTryNext,
  903. .wake_fd = engine.ws_loop_wake_fd, // mission 256 — set by wsEnsureStarted above
  904. .head_stamp_fn = &wsEventsHeadStamp,
  905. };
  906. return api.makeIterator(iter);
  907. }
  908. // --- cookie-grade random (mission 093) ------------------------------------
  909. // A session id is the ONLY thing standing between a stranger and someone else's
  910. // session, so it may not come from a seeded PRNG: `hl:math`'s random() is a
  911. // clock-seeded xoshiro, and a few of its outputs reveal its state, which would
  912. // make every other session's id derivable from one's own. This reads the
  913. // kernel's CSPRNG directly. It lives in hl:http1 because the session cookie is
  914. // an HTTP artifact and this plugin is the one that parses and sets it; there is
  915. // no other CSPRNG at the hl: level yet (named as a gap in mission 093's report).
  916. var token_buf: [128]u8 = undefined;
  917. /// __native("http1.random_token", n) → n lowercase hex chars (default 32, max 128)
  918. export fn hl_http1_random_token(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  919. var want: usize = 32;
  920. if (argc >= 1 and argv[0].type == .hl_number) {
  921. const n = argv[0].data.number;
  922. if (n >= 1 and n <= 128) want = @intFromFloat(n);
  923. }
  924. var raw: [64]u8 = undefined;
  925. const need = (want + 1) / 2;
  926. if (linux.getrandom(&raw, need, 0) != need) return api.makeNull();
  927. const hex = "0123456789abcdef";
  928. var i: usize = 0;
  929. while (i < want) : (i += 1) {
  930. const byte = raw[i / 2];
  931. const nib: u8 = if (i % 2 == 0) (byte >> 4) else (byte & 0x0f);
  932. token_buf[i] = hex[nib];
  933. }
  934. return api.makeString(token_buf[0..want]);
  935. }
  936. /// __native("http1.ws_send", id, text[, binaryFlag]) → 1 sent / 0 gone
  937. export fn hl_http1_ws_send(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  938. if (argc < 2 or argv[0].type != .hl_number or argv[1].type != .hl_string) return api.makeNumber(0);
  939. const id: u32 = @intFromFloat(argv[0].data.number);
  940. const engine = wsEngineForClient(id) orelse return api.makeNumber(0);
  941. const text = argv[1].data.string.ptr[0..argv[1].data.string.len];
  942. const opcode: ws.Opcode = if (argc >= 3 and argv[2].type == .hl_bool and argv[2].data.boolean) .binary else .text;
  943. mutexLock(&engine.ws_mutex);
  944. defer mutexUnlock(&engine.ws_mutex);
  945. const idx = wsFindByIdLocked(engine, id) orelse return api.makeNumber(0);
  946. const client = engine.ws_clients.items[idx];
  947. if (!ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), opcode, text)) {
  948. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  949. wsRemoveLocked(engine, idx);
  950. return api.makeNumber(0);
  951. }
  952. return api.makeNumber(1);
  953. }
  954. /// __native("http1.ws_broadcast", text) → number of clients written
  955. export fn hl_http1_ws_broadcast(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  956. if (argc < 1 or argv[0].type != .hl_string) return api.makeNumber(0);
  957. const engine = wsEngineForPort(argc, argv, 1) orelse return api.makeNumber(0);
  958. const text = argv[0].data.string.ptr[0..argv[0].data.string.len];
  959. mutexLock(&engine.ws_mutex);
  960. defer mutexUnlock(&engine.ws_mutex);
  961. var count: usize = 0;
  962. var i: usize = 0;
  963. while (i < engine.ws_clients.items.len) {
  964. const client = engine.ws_clients.items[i];
  965. if (ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .text, text)) {
  966. count += 1;
  967. i += 1;
  968. } else {
  969. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  970. wsRemoveLocked(engine, i);
  971. }
  972. }
  973. return api.makeNumber(@floatFromInt(count));
  974. }
  975. /// __native("http1.ws_ping", id) → 1 sent / 0 gone
  976. export fn hl_http1_ws_ping(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  977. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  978. const id: u32 = @intFromFloat(argv[0].data.number);
  979. const engine = wsEngineForClient(id) orelse return api.makeNumber(0);
  980. mutexLock(&engine.ws_mutex);
  981. defer mutexUnlock(&engine.ws_mutex);
  982. const idx = wsFindByIdLocked(engine, id) orelse return api.makeNumber(0);
  983. const client = engine.ws_clients.items[idx];
  984. if (!ws.writeFrame(&wsFdWrite, wsFdCtx(client.fd), .ping, "")) {
  985. wsRemoveLocked(engine, idx);
  986. return api.makeNumber(0);
  987. }
  988. return api.makeNumber(1);
  989. }
  990. /// __native("http1.ws_close", id[, code]) → 1 initiated / 0 gone.
  991. /// Sends the close frame and waits for the peer echo (reader completes it).
  992. export fn hl_http1_ws_close(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  993. if (argc < 1 or argv[0].type != .hl_number) return api.makeNumber(0);
  994. const id: u32 = @intFromFloat(argv[0].data.number);
  995. const engine = wsEngineForClient(id) orelse return api.makeNumber(0);
  996. const code: u16 = if (argc >= 2 and argv[1].type == .hl_number) @intFromFloat(argv[1].data.number) else ws.CLOSE_NORMAL;
  997. mutexLock(&engine.ws_mutex);
  998. defer mutexUnlock(&engine.ws_mutex);
  999. const idx = wsFindByIdLocked(engine, id) orelse return api.makeNumber(0);
  1000. const client = engine.ws_clients.items[idx];
  1001. if (!ws.writeClose(&wsFdWrite, wsFdCtx(client.fd), code, "")) {
  1002. wsQueue(engine, .{ .kind = .close, .id = client.id, .code = 1006 }) catch {};
  1003. wsRemoveLocked(engine, idx);
  1004. return api.makeNumber(0);
  1005. }
  1006. client.closing = true;
  1007. return api.makeNumber(1);
  1008. }
  1009. // =========================================================================
  1010. // TLS context — OpenSSL via dlopen (optional, no compile-time dep)
  1011. // =========================================================================
  1012. const c_dlfcn = @cImport({
  1013. @cInclude("dlfcn.h");
  1014. });
  1015. const SSL_CTX = opaque {};
  1016. const SSL = opaque {};
  1017. const SSL_METHOD = opaque {};
  1018. // OpenSSL function pointer types
  1019. const SSL_library_init_fn = *const fn () callconv(.c) c_int;
  1020. const SSL_load_error_strings_fn = *const fn () callconv(.c) void;
  1021. const TLS_server_method_fn = *const fn () callconv(.c) ?*const SSL_METHOD;
  1022. const SSL_CTX_new_fn = *const fn (?*const SSL_METHOD) callconv(.c) ?*SSL_CTX;
  1023. const SSL_CTX_free_fn = *const fn (?*SSL_CTX) callconv(.c) void;
  1024. const SSL_CTX_use_certificate_chain_file_fn = *const fn (?*SSL_CTX, [*:0]const u8) callconv(.c) c_int;
  1025. const SSL_CTX_use_PrivateKey_file_fn = *const fn (?*SSL_CTX, [*:0]const u8, c_int) callconv(.c) c_int;
  1026. const SSL_new_fn = *const fn (?*SSL_CTX) callconv(.c) ?*SSL;
  1027. const SSL_free_fn = *const fn (?*SSL) callconv(.c) void;
  1028. const SSL_set_fd_fn = *const fn (?*SSL, c_int) callconv(.c) c_int;
  1029. const SSL_accept_fn = *const fn (?*SSL) callconv(.c) c_int;
  1030. const SSL_read_fn = *const fn (?*SSL, [*]u8, c_int) callconv(.c) c_int;
  1031. const SSL_write_fn = *const fn (?*SSL, [*]const u8, c_int) callconv(.c) c_int;
  1032. const SSL_shutdown_fn = *const fn (?*SSL) callconv(.c) c_int;
  1033. const SSL_get_error_fn = *const fn (?*SSL, c_int) callconv(.c) c_int;
  1034. const OPENSSL_init_ssl_fn = *const fn (u64, ?*anyopaque) callconv(.c) c_int;
  1035. const SSL_FILETYPE_PEM: c_int = 1;
  1036. const TlsContext = struct {
  1037. ssl_ctx: ?*SSL_CTX = null,
  1038. lib_ssl: ?*anyopaque = null,
  1039. lib_crypto: ?*anyopaque = null,
  1040. // Function pointers
  1041. fn_ssl_ctx_new: ?SSL_CTX_new_fn = null,
  1042. fn_ssl_ctx_free: ?SSL_CTX_free_fn = null,
  1043. fn_ssl_ctx_use_cert: ?SSL_CTX_use_certificate_chain_file_fn = null,
  1044. fn_ssl_ctx_use_key: ?SSL_CTX_use_PrivateKey_file_fn = null,
  1045. fn_ssl_new: ?SSL_new_fn = null,
  1046. fn_ssl_free: ?SSL_free_fn = null,
  1047. fn_ssl_set_fd: ?SSL_set_fd_fn = null,
  1048. fn_ssl_accept: ?SSL_accept_fn = null,
  1049. fn_ssl_read: ?SSL_read_fn = null,
  1050. fn_ssl_write: ?SSL_write_fn = null,
  1051. fn_ssl_shutdown: ?SSL_shutdown_fn = null,
  1052. fn_ssl_get_error: ?SSL_get_error_fn = null,
  1053. fn loadSym(lib: ?*anyopaque, comptime T: type, name: [*:0]const u8) ?T {
  1054. const sym = c_dlfcn.dlsym(lib, name) orelse return null;
  1055. return @ptrCast(sym);
  1056. }
  1057. fn init(cert_path: []const u8, key_path: []const u8) ?TlsContext {
  1058. var ctx = TlsContext{};
  1059. // Try loading libssl and libcrypto
  1060. const ssl_paths = [_][*:0]const u8{ "libssl.so.3", "libssl.so.1.1", "libssl.so" };
  1061. const crypto_paths = [_][*:0]const u8{ "libcrypto.so.3", "libcrypto.so.1.1", "libcrypto.so" };
  1062. for (ssl_paths) |path| {
  1063. ctx.lib_ssl = c_dlfcn.dlopen(path, c_dlfcn.RTLD_NOW | c_dlfcn.RTLD_LOCAL);
  1064. if (ctx.lib_ssl != null) break;
  1065. }
  1066. if (ctx.lib_ssl == null) {
  1067. logMsg("http1: TLS: failed to load libssl.so\n");
  1068. return null;
  1069. }
  1070. for (crypto_paths) |path| {
  1071. ctx.lib_crypto = c_dlfcn.dlopen(path, c_dlfcn.RTLD_NOW | c_dlfcn.RTLD_LOCAL);
  1072. if (ctx.lib_crypto != null) break;
  1073. }
  1074. if (ctx.lib_crypto == null) {
  1075. logMsg("http1: TLS: failed to load libcrypto.so\n");
  1076. _ = c_dlfcn.dlclose(ctx.lib_ssl);
  1077. return null;
  1078. }
  1079. // Load function pointers
  1080. // Try OPENSSL_init_ssl first (OpenSSL 1.1+), fall back to SSL_library_init
  1081. if (loadSym(ctx.lib_ssl, OPENSSL_init_ssl_fn, "OPENSSL_init_ssl")) |init_fn| {
  1082. _ = init_fn(0, null);
  1083. } else if (loadSym(ctx.lib_ssl, SSL_library_init_fn, "SSL_library_init")) |lib_init| {
  1084. _ = lib_init();
  1085. if (loadSym(ctx.lib_ssl, SSL_load_error_strings_fn, "SSL_load_error_strings")) |load_err| {
  1086. load_err();
  1087. }
  1088. }
  1089. const method_fn = loadSym(ctx.lib_ssl, TLS_server_method_fn, "TLS_server_method") orelse {
  1090. logMsg("http1: TLS: TLS_server_method not found\n");
  1091. ctx.deinit();
  1092. return null;
  1093. };
  1094. ctx.fn_ssl_ctx_new = loadSym(ctx.lib_ssl, SSL_CTX_new_fn, "SSL_CTX_new");
  1095. ctx.fn_ssl_ctx_free = loadSym(ctx.lib_ssl, SSL_CTX_free_fn, "SSL_CTX_free");
  1096. ctx.fn_ssl_ctx_use_cert = loadSym(ctx.lib_ssl, SSL_CTX_use_certificate_chain_file_fn, "SSL_CTX_use_certificate_chain_file");
  1097. ctx.fn_ssl_ctx_use_key = loadSym(ctx.lib_ssl, SSL_CTX_use_PrivateKey_file_fn, "SSL_CTX_use_PrivateKey_file");
  1098. ctx.fn_ssl_new = loadSym(ctx.lib_ssl, SSL_new_fn, "SSL_new");
  1099. ctx.fn_ssl_free = loadSym(ctx.lib_ssl, SSL_free_fn, "SSL_free");
  1100. ctx.fn_ssl_set_fd = loadSym(ctx.lib_ssl, SSL_set_fd_fn, "SSL_set_fd");
  1101. ctx.fn_ssl_accept = loadSym(ctx.lib_ssl, SSL_accept_fn, "SSL_accept");
  1102. ctx.fn_ssl_read = loadSym(ctx.lib_ssl, SSL_read_fn, "SSL_read");
  1103. ctx.fn_ssl_write = loadSym(ctx.lib_ssl, SSL_write_fn, "SSL_write");
  1104. ctx.fn_ssl_shutdown = loadSym(ctx.lib_ssl, SSL_shutdown_fn, "SSL_shutdown");
  1105. ctx.fn_ssl_get_error = loadSym(ctx.lib_ssl, SSL_get_error_fn, "SSL_get_error");
  1106. if (ctx.fn_ssl_ctx_new == null or ctx.fn_ssl_new == null or
  1107. ctx.fn_ssl_set_fd == null or ctx.fn_ssl_accept == null or
  1108. ctx.fn_ssl_read == null or ctx.fn_ssl_write == null)
  1109. {
  1110. logMsg("http1: TLS: missing required SSL symbols\n");
  1111. ctx.deinit();
  1112. return null;
  1113. }
  1114. // Create SSL_CTX
  1115. const method = method_fn();
  1116. ctx.ssl_ctx = ctx.fn_ssl_ctx_new.?(method);
  1117. if (ctx.ssl_ctx == null) {
  1118. logMsg("http1: TLS: SSL_CTX_new failed\n");
  1119. ctx.deinit();
  1120. return null;
  1121. }
  1122. // Load cert and key
  1123. const cert_z = allocator.dupeZ(u8, cert_path) catch {
  1124. ctx.deinit();
  1125. return null;
  1126. };
  1127. defer allocator.free(cert_z);
  1128. const key_z = allocator.dupeZ(u8, key_path) catch {
  1129. ctx.deinit();
  1130. return null;
  1131. };
  1132. defer allocator.free(key_z);
  1133. if (ctx.fn_ssl_ctx_use_cert) |use_cert| {
  1134. if (use_cert(ctx.ssl_ctx, cert_z.ptr) != 1) {
  1135. logFmt("http1: TLS: failed to load certificate: {s}\n", .{cert_path});
  1136. ctx.deinit();
  1137. return null;
  1138. }
  1139. }
  1140. if (ctx.fn_ssl_ctx_use_key) |use_key| {
  1141. if (use_key(ctx.ssl_ctx, key_z.ptr, SSL_FILETYPE_PEM) != 1) {
  1142. logFmt("http1: TLS: failed to load private key: {s}\n", .{key_path});
  1143. ctx.deinit();
  1144. return null;
  1145. }
  1146. }
  1147. logMsg("http1: TLS initialized\n");
  1148. return ctx;
  1149. }
  1150. fn wrapConnection(self: *const TlsContext, fd: i32) ?*SSL {
  1151. const ssl = self.fn_ssl_new.?(self.ssl_ctx);
  1152. if (ssl == null) return null;
  1153. _ = self.fn_ssl_set_fd.?(ssl, fd);
  1154. const ret = self.fn_ssl_accept.?(ssl);
  1155. if (ret != 1) {
  1156. self.fn_ssl_free.?(ssl);
  1157. return null;
  1158. }
  1159. return ssl;
  1160. }
  1161. fn sslRead(self: *const TlsContext, ssl: *SSL, buf: []u8) isize {
  1162. const ret = self.fn_ssl_read.?(ssl, buf.ptr, @intCast(@min(buf.len, std.math.maxInt(c_int))));
  1163. if (ret <= 0) return 0;
  1164. return @intCast(ret);
  1165. }
  1166. fn sslWrite(self: *const TlsContext, ssl: *SSL, data: []const u8) isize {
  1167. var written: usize = 0;
  1168. while (written < data.len) {
  1169. const chunk_len: c_int = @intCast(@min(data.len - written, std.math.maxInt(c_int)));
  1170. const ret = self.fn_ssl_write.?(ssl, data[written..].ptr, chunk_len);
  1171. if (ret <= 0) return @intCast(written);
  1172. written += @intCast(ret);
  1173. }
  1174. return @intCast(written);
  1175. }
  1176. fn sslShutdown(self: *const TlsContext, ssl: *SSL) void {
  1177. _ = self.fn_ssl_shutdown.?(ssl);
  1178. self.fn_ssl_free.?(ssl);
  1179. }
  1180. fn deinit(self: *TlsContext) void {
  1181. if (self.ssl_ctx != null) {
  1182. if (self.fn_ssl_ctx_free) |free_fn| {
  1183. free_fn(self.ssl_ctx);
  1184. }
  1185. self.ssl_ctx = null;
  1186. }
  1187. if (self.lib_ssl != null) {
  1188. _ = c_dlfcn.dlclose(self.lib_ssl);
  1189. self.lib_ssl = null;
  1190. }
  1191. if (self.lib_crypto != null) {
  1192. _ = c_dlfcn.dlclose(self.lib_crypto);
  1193. self.lib_crypto = null;
  1194. }
  1195. }
  1196. };
  1197. // =========================================================================
  1198. // MPSC Request Queue — thread-safe, blocks on dequeue
  1199. // =========================================================================
  1200. const ParsedRequest = struct {
  1201. method: []const u8,
  1202. path: []const u8, // URL-decoded
  1203. query_params: []http.QueryParam, // parsed key-value pairs
  1204. query_raw: []const u8, // raw query string
  1205. headers: std.ArrayListUnmanaged(HeaderPair),
  1206. body: []const u8,
  1207. client_fd: i32,
  1208. ssl: ?*SSL, // null if plain HTTP
  1209. keep_alive: bool,
  1210. };
  1211. const HeaderPair = struct {
  1212. key: []const u8,
  1213. value: []const u8,
  1214. };
  1215. const RequestQueue = struct {
  1216. queue: std.ArrayListUnmanaged(ParsedRequest),
  1217. mutex: PthreadMutex,
  1218. condvar: PthreadCond,
  1219. shutdown: bool,
  1220. /// THE EVENT LOOP'S BELL (mission 256). The condvar above wakes a `for (req of
  1221. /// server)` consumer blocked in `dequeue`; the interpreter's event loop is
  1222. /// NOT that consumer — it polls `tryDequeue` from a loop that also watches
  1223. /// every other source, so it cannot block on a condvar belonging to one of
  1224. /// them. An eventfd it can: `native/src/loop_wait.zig` epolls this fd, and an
  1225. /// idle server costs nothing instead of 1000 empty poll rounds a second.
  1226. loop_wake_fd: i32,
  1227. fn init() RequestQueue {
  1228. var self: RequestQueue = .{
  1229. .queue = .empty,
  1230. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1231. .condvar = c.PTHREAD_COND_INITIALIZER,
  1232. .shutdown = false,
  1233. .loop_wake_fd = http.makeWakeFd(),
  1234. };
  1235. mutexInit(&self.mutex);
  1236. condInit(&self.condvar);
  1237. return self;
  1238. }
  1239. fn enqueue(self: *RequestQueue, req: ParsedRequest) void {
  1240. mutexLock(&self.mutex);
  1241. defer mutexUnlock(&self.mutex);
  1242. self.queue.append(allocator, req) catch return;
  1243. condSignal(&self.condvar);
  1244. // Rung INSIDE the lock, so the fd's counter is already up by the time the
  1245. // request is visible to `tryDequeue`. A loop that is between its last poll
  1246. // and its next `epoll_wait` therefore finds the level raised and returns
  1247. // at once instead of sleeping on a queue that has work in it.
  1248. http.ringWake(self.loop_wake_fd);
  1249. }
  1250. fn dequeue(self: *RequestQueue) ?ParsedRequest {
  1251. mutexLock(&self.mutex);
  1252. defer mutexUnlock(&self.mutex);
  1253. while (self.queue.items.len == 0 and !self.shutdown) {
  1254. condWait(&self.condvar, &self.mutex);
  1255. }
  1256. if (self.shutdown and self.queue.items.len == 0) return null;
  1257. const req = self.queue.orderedRemove(0);
  1258. if (self.queue.items.len > 0) http.ringWake(self.loop_wake_fd);
  1259. return req;
  1260. }
  1261. /// Non-blocking: returns null immediately if queue is empty
  1262. fn tryDequeue(self: *RequestQueue) ?ParsedRequest {
  1263. mutexLock(&self.mutex);
  1264. defer mutexUnlock(&self.mutex);
  1265. if (self.queue.items.len == 0) return null;
  1266. const req = self.queue.orderedRemove(0);
  1267. if (self.queue.items.len > 0) http.ringWake(self.loop_wake_fd);
  1268. return req;
  1269. }
  1270. fn signalShutdown(self: *RequestQueue) void {
  1271. mutexLock(&self.mutex);
  1272. defer mutexUnlock(&self.mutex);
  1273. self.shutdown = true;
  1274. condBroadcast(&self.condvar);
  1275. // The event loop is told too — it is blocked on this fd and its `while`
  1276. // condition (has every source retired?) can only be re-read on the way out.
  1277. http.ringWake(self.loop_wake_fd);
  1278. }
  1279. fn deinit(self: *RequestQueue) void {
  1280. // Free any remaining queued requests
  1281. for (self.queue.items) |*req| {
  1282. freeRequest(req);
  1283. }
  1284. self.queue.deinit(allocator);
  1285. if (self.loop_wake_fd >= 0) {
  1286. _ = linux.close(self.loop_wake_fd);
  1287. self.loop_wake_fd = -1;
  1288. }
  1289. _ = c.pthread_cond_destroy(&self.condvar);
  1290. _ = c.pthread_mutex_destroy(&self.mutex);
  1291. }
  1292. };
  1293. fn freeRequest(req: *ParsedRequest) void {
  1294. allocator.free(req.method);
  1295. allocator.free(req.path);
  1296. allocator.free(req.query_raw);
  1297. for (req.query_params) |param| {
  1298. allocator.free(param.key);
  1299. allocator.free(param.value);
  1300. }
  1301. allocator.free(req.query_params);
  1302. for (req.headers.items) |hdr| {
  1303. allocator.free(hdr.key);
  1304. allocator.free(hdr.value);
  1305. }
  1306. req.headers.deinit(allocator);
  1307. if (req.body.len > 0) allocator.free(req.body);
  1308. }
  1309. // =========================================================================
  1310. // Connection — per-connection state tracked by I/O workers
  1311. // =========================================================================
  1312. const Connection = struct {
  1313. fd: i32,
  1314. ssl: ?*SSL,
  1315. keep_alive: bool,
  1316. request_count: u32,
  1317. max_requests: u32,
  1318. fn read(self: *const Connection, tls: ?*const TlsContext, buf: []u8) usize {
  1319. if (self.ssl) |ssl_ptr| {
  1320. if (tls) |t| {
  1321. const n = t.sslRead(ssl_ptr, buf);
  1322. if (n <= 0) return 0;
  1323. return @intCast(n);
  1324. }
  1325. return 0;
  1326. }
  1327. return sysRead(self.fd, buf);
  1328. }
  1329. fn write(self: *const Connection, tls: ?*const TlsContext, data: []const u8) void {
  1330. if (self.ssl) |ssl_ptr| {
  1331. if (tls) |t| {
  1332. _ = t.sslWrite(ssl_ptr, data);
  1333. return;
  1334. }
  1335. }
  1336. sysWriteAll(self.fd, data);
  1337. }
  1338. fn close(self: *Connection, tls: ?*const TlsContext) void {
  1339. if (self.ssl) |ssl_ptr| {
  1340. if (tls) |t| {
  1341. t.sslShutdown(ssl_ptr);
  1342. }
  1343. self.ssl = null;
  1344. }
  1345. _ = linux.close(self.fd);
  1346. }
  1347. };
  1348. // =========================================================================
  1349. // ServerCore — owns server socket, epoll, threads, queue, optional TLS
  1350. // =========================================================================
  1351. const MAX_KEEPALIVE_REQUESTS: u32 = 100;
  1352. const MAX_IO_THREADS: u32 = 16;
  1353. const ServerCore = struct {
  1354. port: u16 = 0,
  1355. websocket: *WsEngine,
  1356. server_fd: i32,
  1357. epoll_fd: i32,
  1358. shutdown_fd: i32, // eventfd for shutdown signal
  1359. tls: ?TlsContext,
  1360. request_queue: RequestQueue,
  1361. running: std.atomic.Value(bool),
  1362. acceptor_thread: ?std.Thread,
  1363. io_threads: []std.Thread,
  1364. num_threads: u32,
  1365. // Connection tracking for I/O threads
  1366. conn_queue: ConnectionQueue,
  1367. /// idle connections wait here instead of inside a blocking worker read (mission 084)
  1368. parked: ParkedConns,
  1369. /// Largest request body this server reads (ticket #445): a bigger Content-Length, or a
  1370. /// chunked body that grows past it, is refused `413` before the body is buffered.
  1371. max_body: usize = DEFAULT_MAX_BODY,
  1372. /// Refuse a WebSocket upgrade whose Origin is foreign with `403` before the 101 (#445).
  1373. ws_check_origin: bool = false,
  1374. /// Extra allowed origins (comma-separated, `scheme://host[:port]` or bare `host[:port]`);
  1375. /// owned copy, empty = none.
  1376. ws_origins: []const u8 = "",
  1377. fn create(port: u16, host_str: []const u8, cert_path: []const u8, key_path: []const u8, num_threads: u32) ?*ServerCore {
  1378. const core = allocator.create(ServerCore) catch return null;
  1379. const engine = allocator.create(WsEngine) catch {
  1380. allocator.destroy(core);
  1381. return null;
  1382. };
  1383. engine.* = .{};
  1384. core.* = .{
  1385. .websocket = engine,
  1386. .server_fd = -1,
  1387. .epoll_fd = -1,
  1388. .shutdown_fd = -1,
  1389. .tls = null,
  1390. .request_queue = RequestQueue.init(),
  1391. .running = std.atomic.Value(bool).init(false),
  1392. .acceptor_thread = null,
  1393. .io_threads = &[_]std.Thread{},
  1394. .num_threads = @min(num_threads, MAX_IO_THREADS),
  1395. .conn_queue = ConnectionQueue.init(),
  1396. .parked = ParkedConns.init(),
  1397. };
  1398. // Create TCP socket. NONBLOCK IS NOT DECORATION (mission 260): the acceptor
  1399. // drains with `while (true) accept4(...)` until the call fails, and on a
  1400. // BLOCKING listener that last call does not fail — it sleeps in the kernel
  1401. // (`inet_csk_accept`) until the next client arrives. The thread then never
  1402. // re-reads `core.running`, so `shutdown()`'s `join(acceptor)` waits forever
  1403. // and `close()` never returns. Measured: after ONE connection the process was
  1404. // down to two threads, main in `__futex_wait` (the join) and the acceptor in
  1405. // `inet_csk_accept`; each extra TCP connect added exactly one fd and put the
  1406. // acceptor straight back into `inet_csk_accept`. hl:http2's listener
  1407. // (`http2.zig:926`) has always carried NONBLOCK — http1 was the outlier.
  1408. // The accept flags below apply to the ACCEPTED socket, never to this one.
  1409. const sock_rc = linux.socket(linux.AF.INET, linux.SOCK.STREAM | linux.SOCK.CLOEXEC | linux.SOCK.NONBLOCK, 0);
  1410. const server_fd: i32 = @bitCast(@as(u32, @truncate(sock_rc)));
  1411. if (server_fd < 0) {
  1412. logMsg("http1: socket() failed\n");
  1413. allocator.destroy(core);
  1414. return null;
  1415. }
  1416. core.server_fd = server_fd;
  1417. // SO_REUSEADDR
  1418. const one: i32 = 1;
  1419. _ = linux.setsockopt(server_fd, linux.SOL.SOCKET, linux.SO.REUSEADDR, @ptrCast(&one), @sizeOf(i32));
  1420. // Parse host address
  1421. var addr_val: u32 = 0; // INADDR_ANY
  1422. if (host_str.len > 0 and !std.mem.eql(u8, host_str, "0.0.0.0")) {
  1423. addr_val = parseIPv4(host_str) orelse 0;
  1424. }
  1425. // Bind
  1426. const addr = linux.sockaddr.in{
  1427. .port = std.mem.nativeToBig(u16, port),
  1428. .addr = addr_val,
  1429. };
  1430. const bind_rc = linux.bind(server_fd, @ptrCast(&addr), @sizeOf(linux.sockaddr.in));
  1431. const bind_err: i32 = @bitCast(@as(u32, @truncate(bind_rc)));
  1432. if (bind_err < 0) {
  1433. // The prefix is LOAD-BEARING: `tests/browser/fixtures.mjs` breaks its
  1434. // readiness wait on `bind() failed on port N` (mission 285). The errno
  1435. // and the holder are appended to it, never in front of it.
  1436. var why: [320]u8 = undefined;
  1437. logFmt("http1: bind() failed on port {d}: {s}\n", .{ port, http.bindFailureDetail(&why, bind_rc, port, false) });
  1438. core.destroy();
  1439. return null;
  1440. }
  1441. const listen_rc = linux.listen(server_fd, 128);
  1442. const listen_err: i32 = @bitCast(@as(u32, @truncate(listen_rc)));
  1443. if (listen_err < 0) {
  1444. logMsg("http1: listen() failed\n");
  1445. core.destroy();
  1446. return null;
  1447. }
  1448. // Create eventfd for shutdown signaling
  1449. const efd_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  1450. const shutdown_fd: i32 = @bitCast(@as(u32, @truncate(efd_rc)));
  1451. if (shutdown_fd < 0) {
  1452. logMsg("http1: eventfd() failed\n");
  1453. core.destroy();
  1454. return null;
  1455. }
  1456. core.shutdown_fd = shutdown_fd;
  1457. // Create epoll instance
  1458. const epoll_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  1459. const epoll_fd: i32 = @bitCast(@as(u32, @truncate(epoll_rc)));
  1460. if (epoll_fd < 0) {
  1461. logMsg("http1: epoll_create1() failed\n");
  1462. core.destroy();
  1463. return null;
  1464. }
  1465. core.epoll_fd = epoll_fd;
  1466. // Add server_fd to epoll
  1467. var ev = linux.epoll_event{
  1468. .events = linux.EPOLL.IN,
  1469. .data = .{ .fd = server_fd },
  1470. };
  1471. _ = linux.epoll_ctl(epoll_fd, linux.EPOLL.CTL_ADD, server_fd, &ev);
  1472. // Add shutdown_fd to epoll
  1473. var shutdown_ev = linux.epoll_event{
  1474. .events = linux.EPOLL.IN,
  1475. .data = .{ .fd = shutdown_fd },
  1476. };
  1477. _ = linux.epoll_ctl(epoll_fd, linux.EPOLL.CTL_ADD, shutdown_fd, &shutdown_ev);
  1478. // Initialize TLS if cert+key provided
  1479. if (cert_path.len > 0 and key_path.len > 0) {
  1480. core.tls = TlsContext.init(cert_path, key_path);
  1481. if (core.tls == null) {
  1482. logMsg("http1: TLS initialization failed, falling back to plain HTTP\n");
  1483. }
  1484. }
  1485. logFmt("http1: listening on :{d}{s}\n", .{ port, if (core.tls != null) " (TLS)" else "" });
  1486. // Start threads
  1487. core.running.store(true, .release);
  1488. // Parker thread first: the acceptor parks into it from its very first accept.
  1489. // If it cannot start we log and keep going — connections then go straight to the
  1490. // pool, which is the pre-084 (starvable) behaviour rather than an outage.
  1491. if (!core.parked.start(core)) {
  1492. logMsg("http1: parker thread unavailable — idle keep-alive connections will hold I/O workers\n");
  1493. }
  1494. // Allocate I/O threads
  1495. const threads = allocator.alloc(std.Thread, core.num_threads) catch {
  1496. core.destroy();
  1497. return null;
  1498. };
  1499. core.io_threads = threads;
  1500. for (0..core.num_threads) |i| {
  1501. core.io_threads[i] = std.Thread.spawn(.{}, ioWorker, .{core}) catch {
  1502. logFmt("http1: failed to spawn I/O thread {d}\n", .{i});
  1503. core.num_threads = @intCast(i);
  1504. core.io_threads = core.io_threads[0..i];
  1505. break;
  1506. };
  1507. }
  1508. // Start acceptor thread
  1509. core.acceptor_thread = std.Thread.spawn(.{}, acceptorLoop, .{core}) catch {
  1510. logMsg("http1: failed to spawn acceptor thread\n");
  1511. core.shutdown();
  1512. core.destroy();
  1513. return null;
  1514. };
  1515. core.port = port;
  1516. registerCore(core);
  1517. return core;
  1518. }
  1519. fn shutdown(self: *ServerCore) void {
  1520. unregisterCore(self);
  1521. if (!self.running.swap(false, .acq_rel)) return;
  1522. // Signal shutdown via eventfd
  1523. if (self.shutdown_fd >= 0) {
  1524. const val: u64 = 1;
  1525. _ = linux.write(self.shutdown_fd, @ptrCast(&val), @sizeOf(u64));
  1526. }
  1527. // Wake up the request queue so dequeue() unblocks
  1528. self.request_queue.signalShutdown();
  1529. // Stop parking before the workers: the parker must not push new work into a
  1530. // queue whose consumers are being torn down.
  1531. self.parked.stop();
  1532. // Signal connection queue to wake I/O workers
  1533. self.conn_queue.signalShutdown();
  1534. // Join acceptor thread
  1535. if (self.acceptor_thread) |t| {
  1536. t.join();
  1537. self.acceptor_thread = null;
  1538. }
  1539. // Join I/O threads
  1540. for (self.io_threads) |t| {
  1541. t.join();
  1542. }
  1543. wsShutdown(self.websocket);
  1544. }
  1545. fn destroy(self: *ServerCore) void {
  1546. self.shutdown();
  1547. if (self.epoll_fd >= 0) _ = linux.close(self.epoll_fd);
  1548. if (self.shutdown_fd >= 0) _ = linux.close(self.shutdown_fd);
  1549. if (self.server_fd >= 0) _ = linux.close(self.server_fd);
  1550. if (self.tls) |*tls| tls.deinit();
  1551. // Close every still-parked idle connection, then drain conn_queue
  1552. self.parked.deinit(if (self.tls) |*t| t else null);
  1553. self.conn_queue.deinit(if (self.tls) |*t| t else null);
  1554. self.request_queue.deinit();
  1555. if (self.io_threads.len > 0) allocator.free(self.io_threads);
  1556. allocator.destroy(self);
  1557. }
  1558. };
  1559. // =========================================================================
  1560. // Connection Queue — MPSC queue for acceptor → I/O workers
  1561. // =========================================================================
  1562. const ConnectionQueue = struct {
  1563. queue: std.ArrayListUnmanaged(Connection),
  1564. mutex: PthreadMutex,
  1565. condvar: PthreadCond,
  1566. shutdown: bool,
  1567. fn init() ConnectionQueue {
  1568. var self: ConnectionQueue = .{
  1569. .queue = .empty,
  1570. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1571. .condvar = c.PTHREAD_COND_INITIALIZER,
  1572. .shutdown = false,
  1573. };
  1574. mutexInit(&self.mutex);
  1575. condInit(&self.condvar);
  1576. return self;
  1577. }
  1578. fn enqueue(self: *ConnectionQueue, conn: Connection) void {
  1579. mutexLock(&self.mutex);
  1580. defer mutexUnlock(&self.mutex);
  1581. self.queue.append(allocator, conn) catch return;
  1582. condSignal(&self.condvar);
  1583. }
  1584. fn dequeue(self: *ConnectionQueue) ?Connection {
  1585. mutexLock(&self.mutex);
  1586. defer mutexUnlock(&self.mutex);
  1587. while (self.queue.items.len == 0 and !self.shutdown) {
  1588. condWait(&self.condvar, &self.mutex);
  1589. }
  1590. if (self.shutdown and self.queue.items.len == 0) return null;
  1591. return self.queue.orderedRemove(0);
  1592. }
  1593. fn signalShutdown(self: *ConnectionQueue) void {
  1594. mutexLock(&self.mutex);
  1595. defer mutexUnlock(&self.mutex);
  1596. self.shutdown = true;
  1597. condBroadcast(&self.condvar);
  1598. }
  1599. /// Close everything still queued and stay a VALID, EMPTY queue — `deinit`
  1600. /// leaves the list `undefined`, which is only safe on a core that is being
  1601. /// freed, and a closed core deliberately is not (see `hl_http1_close`).
  1602. fn closeAll(self: *ConnectionQueue, tls: ?*TlsContext) void {
  1603. mutexLock(&self.mutex);
  1604. defer mutexUnlock(&self.mutex);
  1605. for (self.queue.items) |*conn| conn.close(tls);
  1606. self.queue.clearRetainingCapacity();
  1607. }
  1608. fn deinit(self: *ConnectionQueue, tls: ?*TlsContext) void {
  1609. for (self.queue.items) |*conn| {
  1610. conn.close(tls);
  1611. }
  1612. self.queue.deinit(allocator);
  1613. }
  1614. };
  1615. // =========================================================================
  1616. // ParkedConns — idle connections wait HERE, not in an I/O worker (mission 084)
  1617. // =========================================================================
  1618. //
  1619. // The starvation this fixes, measured: a `threads = 4` server, four keep-alive
  1620. // connections that have gone quiet, and every subsequent request times out — each idle
  1621. // socket sat inside a worker's blocking read(). Parking inverts that: an idle connection
  1622. // costs one epoll registration and ZERO threads, and a worker only ever picks up a
  1623. // connection that already has bytes waiting (or has hung up, which it reads as EOF and
  1624. // closes). Connections are parked from the acceptor (a fresh socket may be silent — a
  1625. // pre-connected browser socket routinely is) and after every keep-alive response.
  1626. //
  1627. // TLS caveat: an ESTABLISHED TLS connection is never parked. OpenSSL may hold already-
  1628. // decrypted plaintext in its own buffer, which epoll on the raw fd cannot see, so parking
  1629. // it could hang a live request. `ssl == null` covers all plain HTTP plus the pre-handshake
  1630. // TLS socket (the ClientHello does arrive on the raw fd), which is what the park path takes.
  1631. /// How long a parked, silent connection is kept before it is closed. It costs no thread,
  1632. /// only an fd, so this is generous compared to the old in-worker 30s SO_RCVTIMEO.
  1633. const PARK_IDLE_TIMEOUT_MS: i64 = 60_000;
  1634. /// Milliseconds on CLOCK_MONOTONIC. This zig's `std.time` exposes no timestamp function,
  1635. /// and monotonic is the right clock anyway — a wall-clock step must not expire a live
  1636. /// connection early or keep a dead one parked.
  1637. fn monotonicMs() i64 {
  1638. var ts: linux.timespec = undefined;
  1639. if (linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts) != 0) return 0;
  1640. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  1641. }
  1642. const ParkedConn = struct {
  1643. conn: Connection,
  1644. /// monotonic ms after which this silent connection is closed
  1645. deadline_ms: i64,
  1646. };
  1647. const ParkedConns = struct {
  1648. epoll_fd: i32,
  1649. wake_fd: i32,
  1650. thread: ?std.Thread,
  1651. running: std.atomic.Value(bool),
  1652. mutex: PthreadMutex,
  1653. /// fd → parked connection. Guarded by `mutex`; the parker thread is the only
  1654. /// consumer, park() the only producer, so a plain map is enough.
  1655. map: std.AutoHashMapUnmanaged(i32, ParkedConn),
  1656. fn init() ParkedConns {
  1657. var self: ParkedConns = .{
  1658. .epoll_fd = -1,
  1659. .wake_fd = -1,
  1660. .thread = null,
  1661. .running = std.atomic.Value(bool).init(false),
  1662. .mutex = c.PTHREAD_MUTEX_INITIALIZER,
  1663. .map = .empty,
  1664. };
  1665. mutexInit(&self.mutex);
  1666. return self;
  1667. }
  1668. /// Create the epoll instance + wake eventfd and spawn the parker thread.
  1669. /// Returns false if the kernel objects could not be made — the caller then falls
  1670. /// back to handing connections straight to the pool (old behaviour, still correct,
  1671. /// just starvable).
  1672. fn start(self: *ParkedConns, core: *ServerCore) bool {
  1673. const ep_rc = linux.epoll_create1(linux.EPOLL.CLOEXEC);
  1674. const ep: i32 = @bitCast(@as(u32, @truncate(ep_rc)));
  1675. if (ep < 0) return false;
  1676. const ef_rc = linux.eventfd(0, linux.EFD.CLOEXEC | linux.EFD.NONBLOCK);
  1677. const ef: i32 = @bitCast(@as(u32, @truncate(ef_rc)));
  1678. if (ef < 0) {
  1679. _ = linux.close(ep);
  1680. return false;
  1681. }
  1682. var wake_ev = linux.epoll_event{ .events = linux.EPOLL.IN, .data = .{ .fd = ef } };
  1683. _ = linux.epoll_ctl(ep, linux.EPOLL.CTL_ADD, ef, &wake_ev);
  1684. self.epoll_fd = ep;
  1685. self.wake_fd = ef;
  1686. self.running.store(true, .release);
  1687. self.thread = std.Thread.spawn(.{}, parkerLoop, .{core}) catch {
  1688. self.running.store(false, .release);
  1689. _ = linux.close(ep);
  1690. _ = linux.close(ef);
  1691. self.epoll_fd = -1;
  1692. self.wake_fd = -1;
  1693. return false;
  1694. };
  1695. return true;
  1696. }
  1697. /// Hand a connection to the parker. The map insert happens BEFORE the epoll ADD so
  1698. /// the parker can never see a readable fd it has no entry for.
  1699. fn park(self: *ParkedConns, conn: Connection) bool {
  1700. if (self.epoll_fd < 0 or !self.running.load(.acquire)) return false;
  1701. mutexLock(&self.mutex);
  1702. self.map.put(allocator, conn.fd, .{
  1703. .conn = conn,
  1704. .deadline_ms = monotonicMs() + PARK_IDLE_TIMEOUT_MS,
  1705. }) catch {
  1706. mutexUnlock(&self.mutex);
  1707. return false;
  1708. };
  1709. var ev = linux.epoll_event{
  1710. .events = linux.EPOLL.IN | linux.EPOLL.RDHUP,
  1711. .data = .{ .fd = conn.fd },
  1712. };
  1713. const rc = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_ADD, conn.fd, &ev);
  1714. const err: i32 = @bitCast(@as(u32, @truncate(rc)));
  1715. if (err < 0) {
  1716. _ = self.map.remove(conn.fd);
  1717. mutexUnlock(&self.mutex);
  1718. return false;
  1719. }
  1720. mutexUnlock(&self.mutex);
  1721. return true;
  1722. }
  1723. /// Take a parked connection off the epoll set. Returns it if we still owned it.
  1724. fn take(self: *ParkedConns, fd: i32) ?Connection {
  1725. mutexLock(&self.mutex);
  1726. defer mutexUnlock(&self.mutex);
  1727. const entry = self.map.fetchRemove(fd) orelse return null;
  1728. _ = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_DEL, fd, null);
  1729. return entry.value.conn;
  1730. }
  1731. /// Close every parked connection whose silence outlived PARK_IDLE_TIMEOUT_MS.
  1732. fn sweepExpired(self: *ParkedConns, tls: ?*TlsContext) void {
  1733. const now = monotonicMs();
  1734. mutexLock(&self.mutex);
  1735. defer mutexUnlock(&self.mutex);
  1736. var expired: [64]i32 = undefined;
  1737. var n: usize = 0;
  1738. var it = self.map.iterator();
  1739. while (it.next()) |kv| {
  1740. if (kv.value_ptr.deadline_ms <= now) {
  1741. if (n == expired.len) break;
  1742. expired[n] = kv.key_ptr.*;
  1743. n += 1;
  1744. }
  1745. }
  1746. for (expired[0..n]) |fd| {
  1747. if (self.map.fetchRemove(fd)) |e| {
  1748. _ = linux.epoll_ctl(self.epoll_fd, linux.EPOLL.CTL_DEL, fd, null);
  1749. var conn = e.value.conn;
  1750. conn.close(tls);
  1751. }
  1752. }
  1753. }
  1754. fn stop(self: *ParkedConns) void {
  1755. if (!self.running.swap(false, .acq_rel)) return;
  1756. if (self.wake_fd >= 0) {
  1757. const val: u64 = 1;
  1758. _ = linux.write(self.wake_fd, @ptrCast(&val), @sizeOf(u64));
  1759. }
  1760. if (self.thread) |t| {
  1761. t.join();
  1762. self.thread = null;
  1763. }
  1764. }
  1765. /// Close every parked connection and stay a VALID, EMPTY map. Unlike `deinit`
  1766. /// this keeps the epoll/wake fds and the struct usable — a CLOSED core is not
  1767. /// a freed one (`hl_http1_close`), and `park()` already refuses once `running`
  1768. /// is false, so the emptied map simply stays empty.
  1769. fn closeAll(self: *ParkedConns, tls: ?*TlsContext) void {
  1770. mutexLock(&self.mutex);
  1771. defer mutexUnlock(&self.mutex);
  1772. var it = self.map.iterator();
  1773. while (it.next()) |kv| {
  1774. var conn = kv.value_ptr.conn;
  1775. conn.close(tls);
  1776. }
  1777. self.map.clearRetainingCapacity();
  1778. }
  1779. fn deinit(self: *ParkedConns, tls: ?*TlsContext) void {
  1780. self.stop();
  1781. mutexLock(&self.mutex);
  1782. var it = self.map.iterator();
  1783. while (it.next()) |kv| {
  1784. var conn = kv.value_ptr.conn;
  1785. conn.close(tls);
  1786. }
  1787. self.map.deinit(allocator);
  1788. self.map = .empty;
  1789. mutexUnlock(&self.mutex);
  1790. if (self.epoll_fd >= 0) _ = linux.close(self.epoll_fd);
  1791. if (self.wake_fd >= 0) _ = linux.close(self.wake_fd);
  1792. self.epoll_fd = -1;
  1793. self.wake_fd = -1;
  1794. }
  1795. };
  1796. /// The parker thread: waits for a parked connection to become READABLE and only then
  1797. /// hands it to an I/O worker. The 1s epoll timeout doubles as the idle-sweep tick.
  1798. fn parkerLoop(core: *ServerCore) void {
  1799. var events: [64]linux.epoll_event = undefined;
  1800. while (core.parked.running.load(.acquire)) {
  1801. const n_rc = linux.epoll_wait(core.parked.epoll_fd, &events, events.len, 1000);
  1802. const n: i32 = @bitCast(@as(u32, @truncate(n_rc)));
  1803. if (n > 0) {
  1804. for (events[0..@intCast(n)]) |ev| {
  1805. if (ev.data.fd == core.parked.wake_fd) {
  1806. var drain: u64 = 0;
  1807. _ = linux.read(core.parked.wake_fd, @ptrCast(&drain), @sizeOf(u64));
  1808. continue;
  1809. }
  1810. // Readable, hung up or errored — all three are a worker's job: it either
  1811. // parses the request or reads EOF and closes.
  1812. if (core.parked.take(ev.data.fd)) |conn| {
  1813. if (core.running.load(.acquire)) {
  1814. core.conn_queue.enqueue(conn);
  1815. } else {
  1816. var dead = conn;
  1817. dead.close(if (core.tls) |*t| t else null);
  1818. }
  1819. }
  1820. }
  1821. }
  1822. core.parked.sweepExpired(if (core.tls) |*t| t else null);
  1823. }
  1824. }
  1825. /// Park `conn` if we can, otherwise hand it straight to the pool. Every enqueue site
  1826. /// that is NOT known to have bytes waiting goes through here.
  1827. fn parkOrEnqueue(core: *ServerCore, conn: Connection) void {
  1828. // An established TLS connection may hold decrypted bytes epoll cannot see — see the
  1829. // ParkedConns header comment. Those go straight to a worker, as before.

Only the first lines are shown.

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre