gitoria

jukebox

All repositories: gitoria

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

76.9 KB

  1. // hl:fetch — the HTTP(S) CLIENT, as a server-realm plugin (mission 135).
  2. //
  3. // Shaped on the web `fetch` the creator already knows: a method, a url, headers and
  4. // a body go out; a status, headers and a body come back. What is NOT web-shaped is
  5. // where the wait happens, and that is the one design decision in this file:
  6. //
  7. // `fetch.start` NEVER WAITS. It hands the request to a thread of its own and
  8. // returns a TICKET (an HlHandle) immediately. `ticket.result()` is the wait.
  9. //
  10. // `fetch()` in server.hl is `fetchStart(…).response()` — start plus wait.
  11. // PendingFetch.response() yields the calling delivery fiber while the worker
  12. // runs; concurrent arms and other event-loop deliveries can keep progressing.
  13. // At the process root there is no delivery fiber, so reading a result can block.
  14. //
  15. // THE EVENT LOOP is never blocked by a fetch in flight: no loop thread is inside a
  16. // socket call, and a completed request rings the mission-125 BELL — `fetch.completions`
  17. // is an ordinary loop source with a `wake_fd`, so an `on fetched(ev)` handler is woken
  18. // by the same `epoll_wait` that wakes an http1 request. (The wait in `result()` is a
  19. // wait like any other plugin call's: it blocks the FIBER that asked. Starting the
  20. // fetches early and reading them later is what keeps a server serving, and the
  21. // completions source is how a server never has to wait at all.)
  22. //
  23. // TLS is `plugins/http/tls_common.zig` — the same module hl:http1 and hl:http2 use,
  24. // extended with a client half in this mission. Verification is ON: system trust
  25. // store plus hostname checking, with `caFile` naming an EXTRA anchor for a test
  26. // fixture's self-signed certificate. There is no verify-off switch at all.
  27. //
  28. // HTTP/1.1 only. An h2 client is a later slice: it needs ALPN on the client side and
  29. // a multiplexed connection pool, neither of which this file has. `connection: close`
  30. // on every request, so there is no pool to keep coherent either.
  31. const std = @import("std");
  32. const api = @import("plugin_api");
  33. const http = @import("http_common");
  34. const tls = @import("tls_common");
  35. const HlValue = api.HlValue;
  36. const HlField = api.HlField;
  37. const HlObject = api.HlObject;
  38. const HlIterator = api.HlIterator;
  39. const HlHandle = api.HlHandle;
  40. const c = @cImport({
  41. @cInclude("netdb.h");
  42. @cInclude("dirent.h");
  43. @cInclude("sys/socket.h");
  44. @cInclude("sys/time.h");
  45. @cInclude("unistd.h");
  46. @cInclude("netinet/in.h");
  47. @cInclude("netinet/tcp.h");
  48. });
  49. // requests run on their own threads: the plugins' allocator (plugin_api.zig)
  50. const allocator = api.allocator;
  51. const linux = std.os.linux;
  52. const libc = std.c;
  53. // pthread rather than std.Thread.Mutex, exactly as hl:http1 does: this is a `.so`
  54. // loaded into a binary built by a possibly different Zig, and the C primitives are
  55. // the ones whose ABI is fixed by the platform rather than by the standard library.
  56. const PthreadMutex = libc.pthread_mutex_t;
  57. const PthreadCond = libc.pthread_cond_t;
  58. fn mutexLock(m: *PthreadMutex) void {
  59. _ = libc.pthread_mutex_lock(m);
  60. }
  61. fn mutexUnlock(m: *PthreadMutex) void {
  62. _ = libc.pthread_mutex_unlock(m);
  63. }
  64. fn condBroadcast(cnd: *PthreadCond) void {
  65. _ = libc.pthread_cond_broadcast(cnd);
  66. }
  67. fn condWait(cnd: *PthreadCond, m: *PthreadMutex) void {
  68. _ = libc.pthread_cond_wait(cnd, m);
  69. }
  70. fn logMsg(msg: []const u8) void {
  71. _ = linux.write(2, msg.ptr, msg.len);
  72. }
  73. fn logFmt(comptime fmt: []const u8, args: anytype) void {
  74. var buf: [512]u8 = undefined;
  75. const s = std.fmt.bufPrint(&buf, fmt, args) catch return;
  76. logMsg(s);
  77. }
  78. // ── Limits, all of them documented defaults rather than hard walls ───────────
  79. /// No answer at all within this many milliseconds is a failed fetch. Overridable
  80. /// per call with `timeoutMs`; it covers the WHOLE exchange (DNS, connect,
  81. /// handshake, request, response, and every redirect hop), not one syscall.
  82. const DEFAULT_TIMEOUT_MS: i64 = 30_000;
  83. /// How many 3xx hops are followed before the fetch fails with "too many redirects".
  84. /// Overridable with `maxRedirects`; 0 means the 3xx is RETURNED as the response.
  85. const DEFAULT_MAX_REDIRECTS: u32 = 5;
  86. /// A response body larger than this fails rather than growing the process without
  87. /// bound — a client that pulls other people's APIs must not be a memory bomb.
  88. const MAX_BODY: usize = 32 * 1024 * 1024;
  89. /// O_NONBLOCK on x86-64 Linux. Spelled here because <fcntl.h> cannot be imported
  90. /// (see tcpConnect); it is an ABI constant, not a libc detail.
  91. const O_NONBLOCK: usize = 0o4000;
  92. const Header = struct {
  93. name: []u8,
  94. value: []u8,
  95. };
  96. fn sameOrigin(a: Url, b: Url) bool {
  97. return a.https == b.https and a.port == b.port and std.ascii.eqlIgnoreCase(a.host, b.host);
  98. }
  99. fn sensitiveHeader(name: []const u8) bool {
  100. return std.ascii.eqlIgnoreCase(name, "authorization") or
  101. std.ascii.eqlIgnoreCase(name, "proxy-authorization") or
  102. std.ascii.eqlIgnoreCase(name, "cookie");
  103. }
  104. fn freeHeaders(list: []Header) void {
  105. for (list) |h| {
  106. allocator.free(h.name);
  107. allocator.free(h.value);
  108. }
  109. allocator.free(list);
  110. }
  111. // ── The request, as the ticket carries it ────────────────────────────────────
  112. const Request = struct {
  113. method: []u8,
  114. url: []u8,
  115. headers: []Header,
  116. body: []u8,
  117. has_body: bool,
  118. json_body: bool,
  119. timeout_ms: i64,
  120. max_redirects: u32,
  121. ca_file: ?[]u8,
  122. tag: []u8,
  123. strip_credentials: bool = false,
  124. drop_body_headers: bool = false,
  125. /// STREAMING (the LLM-token mode): deliver the body INCREMENTALLY as chunk
  126. /// events on the completions source instead of accumulating it. The final
  127. /// completion then carries status/headers and an EMPTY body — the chunks
  128. /// were the body. Requires an armed completions source; `result()` still
  129. /// works and yields the empty-body summary when the stream ends.
  130. stream: bool = false,
  131. fn deinit(self: *Request) void {
  132. allocator.free(self.method);
  133. allocator.free(self.url);
  134. freeHeaders(self.headers);
  135. allocator.free(self.body);
  136. if (self.ca_file) |ca| allocator.free(ca);
  137. allocator.free(self.tag);
  138. }
  139. };
  140. // ── The ticket: one in-flight (or finished) request ──────────────────────────
  141. const Ticket = struct {
  142. mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER,
  143. cond: PthreadCond = libc.PTHREAD_COND_INITIALIZER,
  144. done: bool = false,
  145. thread: ?std.Thread = null,
  146. req: Request,
  147. status: u16 = 0,
  148. final_url: []u8 = &.{},
  149. headers: []Header = &.{},
  150. body: []u8 = &.{},
  151. /// Non-null = the fetch failed and this is the located message the handle
  152. /// hands back as an `hl_error`.
  153. err: ?[]u8 = null,
  154. /// ABORT (the LLM-interrupt primitive): the socket currently carrying this
  155. /// request, visible under the ticket mutex so `fetchAbort(tag)` can
  156. /// shutdown() it from the interpreter thread — the read unblocks, the peer
  157. /// sees the disconnect and stops generating. -1 = none in flight.
  158. live_fd: i32 = -1,
  159. aborted: bool = false,
  160. /// INSTANCE EVENTS (stream mode): a streaming ticket carries its OWN frame
  161. /// queue and bell, created at start — before the worker exists — so no chunk
  162. /// can outrun the arming. `handle.events()` wraps them into a loop source;
  163. /// pending_fetch.hl registers it and re-emits `chunk`/`done` at itself.
  164. /// -1 = not a streaming ticket (completions go the global route, if armed).
  165. ev_queue: std.ArrayListUnmanaged(Completion) = .empty,
  166. ev_wake_fd: i32 = -1,
  167. /// THE PARKED FIBER'S BELL (lazy, under the mutex): `doneFd()` makes an eventfd
  168. /// that finish() rings, so a `concurrent` group whose arms all wait on fetches
  169. /// sleeps in poll() on these instead of spinning. -1 = nobody asked.
  170. done_fd: i32 = -1,
  171. fn doneFd(self: *Ticket) i32 {
  172. mutexLock(&self.mutex);
  173. defer mutexUnlock(&self.mutex);
  174. if (self.done_fd < 0) {
  175. self.done_fd = http.makeWakeFd();
  176. if (self.done and self.done_fd >= 0) http.ringWake(self.done_fd);
  177. }
  178. return self.done_fd;
  179. }
  180. fn wait(self: *Ticket) void {
  181. mutexLock(&self.mutex);
  182. while (!self.done) condWait(&self.cond, &self.mutex);
  183. mutexUnlock(&self.mutex);
  184. }
  185. fn isDone(self: *Ticket) bool {
  186. mutexLock(&self.mutex);
  187. defer mutexUnlock(&self.mutex);
  188. return self.done;
  189. }
  190. fn setLiveFd(self: *Ticket, fd: i32) bool {
  191. mutexLock(&self.mutex);
  192. defer mutexUnlock(&self.mutex);
  193. if (self.aborted) return false; // aborted before the connect landed
  194. self.live_fd = fd;
  195. return true;
  196. }
  197. fn clearLiveFd(self: *Ticket) void {
  198. mutexLock(&self.mutex);
  199. self.live_fd = -1;
  200. mutexUnlock(&self.mutex);
  201. }
  202. /// The abort itself: mark, and shutdown() any in-flight socket so the
  203. /// worker's blocking read returns NOW. Closing is still the worker's job
  204. /// (its defer owns the fd); shutdown only cuts the conversation.
  205. fn abort(self: *Ticket) void {
  206. mutexLock(&self.mutex);
  207. self.aborted = true;
  208. if (self.live_fd >= 0) _ = c.shutdown(self.live_fd, 2); // SHUT_RDWR
  209. mutexUnlock(&self.mutex);
  210. }
  211. fn finish(self: *Ticket) void {
  212. mutexLock(&self.mutex);
  213. self.done = true;
  214. http.ringWake(self.done_fd);
  215. condBroadcast(&self.cond);
  216. mutexUnlock(&self.mutex);
  217. }
  218. fn fail(self: *Ticket, comptime fmt: []const u8, args: anytype) void {
  219. self.err = std.fmt.allocPrint(allocator, fmt, args) catch null;
  220. }
  221. };
  222. // ── URL ──────────────────────────────────────────────────────────────────────
  223. const Url = struct {
  224. https: bool,
  225. host: []const u8,
  226. port: u16,
  227. /// path + query, always starting with '/'
  228. target: []const u8,
  229. };
  230. /// `scheme://host[:port][/path][?query]`. Only http and https; a URL with
  231. /// credentials or an IPv6 literal is refused rather than half-understood.
  232. fn parseUrl(url: []const u8) ?Url {
  233. var rest: []const u8 = undefined;
  234. var https = false;
  235. if (std.mem.startsWith(u8, url, "http://")) {
  236. rest = url["http://".len..];
  237. } else if (std.mem.startsWith(u8, url, "https://")) {
  238. rest = url["https://".len..];
  239. https = true;
  240. } else return null;
  241. const slash = std.mem.indexOfScalar(u8, rest, '/');
  242. const authority = if (slash) |s| rest[0..s] else rest;
  243. const target = if (slash) |s| rest[s..] else "/";
  244. if (authority.len == 0) return null;
  245. if (std.mem.indexOfScalar(u8, authority, '@') != null) return null;
  246. if (std.mem.indexOfScalar(u8, authority, '[') != null) return null;
  247. var host = authority;
  248. var port: u16 = if (https) 443 else 80;
  249. if (std.mem.lastIndexOfScalar(u8, authority, ':')) |colon| {
  250. host = authority[0..colon];
  251. port = std.fmt.parseInt(u16, authority[colon + 1 ..], 10) catch return null;
  252. }
  253. if (host.len == 0) return null;
  254. return .{ .https = https, .host = host, .port = port, .target = target };
  255. }
  256. /// Resolve a `Location` against the URL it came from: absolute stays, `/x` replaces
  257. /// the path, anything else is relative to the current directory of the path.
  258. fn resolveLocation(base: []const u8, loc: []const u8) ?[]u8 {
  259. if (loc.len == 0) return null;
  260. if (std.mem.startsWith(u8, loc, "http://") or std.mem.startsWith(u8, loc, "https://")) {
  261. return allocator.dupe(u8, loc) catch null;
  262. }
  263. const b = parseUrl(base) orelse return null;
  264. const scheme = if (b.https) "https" else "http";
  265. const default_port: u16 = if (b.https) 443 else 80;
  266. var authority_buf: [300]u8 = undefined;
  267. const authority = if (b.port == default_port)
  268. std.fmt.bufPrint(&authority_buf, "{s}", .{b.host}) catch return null
  269. else
  270. std.fmt.bufPrint(&authority_buf, "{s}:{d}", .{ b.host, b.port }) catch return null;
  271. if (loc[0] == '/') {
  272. return std.fmt.allocPrint(allocator, "{s}://{s}{s}", .{ scheme, authority, loc }) catch null;
  273. }
  274. // Relative: cut the base target back to its last '/'.
  275. const path_only = if (std.mem.indexOfScalar(u8, b.target, '?')) |q| b.target[0..q] else b.target;
  276. const cut = std.mem.lastIndexOfScalar(u8, path_only, '/') orelse 0;
  277. return std.fmt.allocPrint(allocator, "{s}://{s}{s}/{s}", .{ scheme, authority, path_only[0..cut], loc }) catch null;
  278. }
  279. // ── Socket plumbing ──────────────────────────────────────────────────────────
  280. fn nowMs() i64 {
  281. var ts: linux.timespec = undefined;
  282. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  283. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  284. }
  285. /// Connect to host:port using the worker's whole-exchange `deadline`. The connect is non-blocking
  286. /// plus a poll so the DEADLINE is honoured even when the peer never answers SYN;
  287. /// the socket is put back into blocking mode with SO_RCVTIMEO/SO_SNDTIMEO after,
  288. /// which is what bounds the read side.
  289. fn tcpConnect(host: []const u8, port: u16, deadline: i64, err_out: *[]const u8) ?i32 {
  290. if (deadline <= nowMs()) {
  291. err_out.* = "timed out";
  292. return null;
  293. }
  294. var host_buf: [256]u8 = undefined;
  295. if (host.len >= host_buf.len) {
  296. err_out.* = "host name too long";
  297. return null;
  298. }
  299. @memcpy(host_buf[0..host.len], host);
  300. host_buf[host.len] = 0;
  301. var port_buf: [8]u8 = undefined;
  302. const port_str = std.fmt.bufPrintZ(&port_buf, "{d}", .{port}) catch {
  303. err_out.* = "bad port";
  304. return null;
  305. };
  306. var hints: c.struct_addrinfo = std.mem.zeroes(c.struct_addrinfo);
  307. hints.ai_family = c.AF_UNSPEC;
  308. hints.ai_socktype = c.SOCK_STREAM;
  309. hints.ai_protocol = c.IPPROTO_TCP;
  310. var res: ?*c.struct_addrinfo = null;
  311. if (c.getaddrinfo(@ptrCast(&host_buf), port_str.ptr, &hints, &res) != 0 or res == null) {
  312. err_out.* = "could not resolve host";
  313. return null;
  314. }
  315. defer c.freeaddrinfo(res);
  316. return tcpConnectAddresses(res, deadline, err_out);
  317. }
  318. // Internal address-list seam: DNS owns the list; this loop owns every pending
  319. // socket until a winner is handed to the caller. A 300 ms stagger starts the next
  320. // address without discarding a slower handshake that still has deadline budget.
  321. fn tcpConnectAddresses(res: ?*c.struct_addrinfo, deadline: i64, err_out: *[]const u8) ?i32 {
  322. var last: []const u8 = "connection failed";
  323. var count: usize = 0;
  324. var it = res;
  325. while (it) |ai| : (it = ai.ai_next) count += 1;
  326. const pending = allocator.alloc(linux.pollfd, count) catch {
  327. err_out.* = last;
  328. return null;
  329. };
  330. defer allocator.free(pending);
  331. for (pending) |*pfd| pfd.* = .{ .fd = -1, .events = linux.POLL.OUT, .revents = 0 };
  332. defer for (pending) |pfd| {
  333. if (pfd.fd >= 0) _ = c.close(pfd.fd);
  334. };
  335. const saved_flags = allocator.alloc(usize, count) catch {
  336. err_out.* = last;
  337. return null;
  338. };
  339. defer allocator.free(saved_flags);
  340. it = res;
  341. var started: usize = 0;
  342. var active: usize = 0;
  343. var next_start = nowMs();
  344. var winner: ?usize = null;
  345. while (it != null or active > 0) {
  346. const now = nowMs();
  347. if (deadline <= now) {
  348. err_out.* = "timed out";
  349. return null;
  350. }
  351. if (it != null and (active == 0 or now >= next_start)) {
  352. const ai = it.?;
  353. it = ai.ai_next;
  354. const index = started;
  355. started += 1;
  356. const fd = c.socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol);
  357. if (fd < 0) {
  358. last = "could not create a socket";
  359. next_start = now;
  360. continue;
  361. }
  362. pending[index].fd = fd;
  363. // Use kernel fcntl: fortified glibc fcntl.h cannot be translated.
  364. const flags = linux.fcntl(fd, linux.F.GETFL, 0);
  365. if (linux.errno(flags) != .SUCCESS or
  366. linux.errno(linux.fcntl(fd, linux.F.SETFL, flags | O_NONBLOCK)) != .SUCCESS)
  367. {
  368. _ = c.close(fd);
  369. pending[index].fd = -1;
  370. last = "connection failed";
  371. next_start = now;
  372. continue;
  373. }
  374. saved_flags[index] = flags;
  375. const rc = c.connect(fd, ai.ai_addr, ai.ai_addrlen);
  376. if (rc == 0) {
  377. winner = index;
  378. break;
  379. }
  380. const connect_err = std.posix.errno(rc);
  381. if (connect_err != .INPROGRESS and connect_err != .INTR and connect_err != .ALREADY) {
  382. last = if (connect_err == .CONNREFUSED) "connection refused" else "connection failed";
  383. _ = c.close(fd);
  384. pending[index].fd = -1;
  385. next_start = now;
  386. continue;
  387. }
  388. active += 1;
  389. next_start = nowMs() + 300;
  390. }
  391. if (active == 0) continue;
  392. const until = if (it != null) @min(deadline, next_start) else deadline;
  393. const wait_ms = @max(until - nowMs(), 0);
  394. // poll ignores closed slots (-1), keeping flags indexed by candidate.
  395. const pr: isize = @bitCast(linux.poll(pending.ptr, @intCast(started), @intCast(@min(wait_ms, std.math.maxInt(i32)))));
  396. if (pr < 0) {
  397. if (linux.errno(@bitCast(pr)) == .INTR) continue;
  398. err_out.* = "connection failed";
  399. return null;
  400. }
  401. if (pr == 0) continue;
  402. for (pending[0..started], 0..) |*pfd, index| {
  403. if (pfd.fd < 0 or pfd.revents == 0) continue;
  404. var so_err: c_int = 0;
  405. var len: c.socklen_t = @sizeOf(c_int);
  406. if (c.getsockopt(pfd.fd, c.SOL_SOCKET, c.SO_ERROR, &so_err, &len) == 0 and so_err == 0) {
  407. winner = index;
  408. break;
  409. }
  410. last = if (so_err == 111) "connection refused" else "connection failed";
  411. _ = c.close(pfd.fd);
  412. pfd.fd = -1;
  413. active -= 1;
  414. // A definitive failure need not consume the rest of its stagger.
  415. if (index + 1 == started) next_start = nowMs();
  416. }
  417. if (winner != null) break;
  418. }
  419. if (winner) |index| {
  420. const fd = pending[index].fd;
  421. if (linux.errno(linux.fcntl(fd, linux.F.SETFL, saved_flags[index])) != .SUCCESS) {
  422. err_out.* = "connection failed";
  423. return null;
  424. }
  425. const left = @max(deadline - nowMs(), 1);
  426. var tv = c.struct_timeval{
  427. .tv_sec = @intCast(@divTrunc(left, 1000)),
  428. .tv_usec = @intCast(@rem(left, 1000) * 1000),
  429. };
  430. _ = c.setsockopt(fd, c.SOL_SOCKET, c.SO_RCVTIMEO, &tv, @sizeOf(c.struct_timeval));
  431. _ = c.setsockopt(fd, c.SOL_SOCKET, c.SO_SNDTIMEO, &tv, @sizeOf(c.struct_timeval));
  432. const one: c_int = 1;
  433. _ = c.setsockopt(fd, c.IPPROTO_TCP, c.TCP_NODELAY, &one, @sizeOf(c_int));
  434. pending[index].fd = -1; // ownership passes to the caller; defer closes losers
  435. return fd;
  436. }
  437. err_out.* = last;
  438. return null;
  439. }
  440. /// The one place either transport is read or written, so the HTTP exchange below
  441. /// is written once for http:// and https://.
  442. const Conn = struct {
  443. fd: i32,
  444. ssl: ?*tls.SSL = null,
  445. tls_ctx: ?*const tls.TlsContext = null,
  446. fn writeAll(self: *Conn, data: []const u8) bool {
  447. if (self.ssl) |ssl| {
  448. return self.tls_ctx.?.writeAll(ssl, data) == data.len;
  449. }
  450. var sent: usize = 0;
  451. while (sent < data.len) {
  452. const n = c.write(self.fd, data.ptr + sent, data.len - sent);
  453. if (n <= 0) return false;
  454. sent += @intCast(n);
  455. }
  456. return true;
  457. }
  458. /// >0 bytes, 0 = clean end of body, <0 = error (or a socket timeout, which the
  459. /// caller separates from an error by looking at the clock).
  460. fn read(self: *Conn, buf: []u8) isize {
  461. if (self.ssl) |ssl| {
  462. const n = self.tls_ctx.?.read(ssl, buf);
  463. if (n > 0) return n;
  464. const e = self.tls_ctx.?.getError(ssl, n);
  465. if (e == tls.SSL_ERROR_ZERO_RETURN) return 0;
  466. return -1;
  467. }
  468. return c.read(self.fd, buf.ptr, buf.len);
  469. }
  470. fn close(self: *Conn) void {
  471. if (self.ssl) |ssl| {
  472. self.tls_ctx.?.shutdownAndFree(ssl);
  473. self.ssl = null;
  474. }
  475. _ = c.close(self.fd);
  476. }
  477. };
  478. // ── The client TLS context, one per CA file ──────────────────────────────────
  479. //
  480. // An SSL_CTX is expensive (it reads the system trust store) and thread-safe, so it
  481. // is built once per distinct `caFile` and shared. The map is tiny by construction:
  482. // a program has a system-trust context and at most a handful of pinned fixtures.
  483. const CtxEntry = struct {
  484. key: []u8,
  485. ctx: tls.TlsContext,
  486. };
  487. var ctx_mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER;
  488. var ctx_list: std.ArrayListUnmanaged(CtxEntry) = .empty;
  489. fn clientCtx(ca_file: ?[]const u8, err_out: *[]const u8) ?*const tls.TlsContext {
  490. const key = ca_file orelse "";
  491. mutexLock(&ctx_mutex);
  492. defer mutexUnlock(&ctx_mutex);
  493. for (ctx_list.items) |*e| {
  494. if (std.mem.eql(u8, e.key, key)) return &e.ctx;
  495. }
  496. const ctx = tls.TlsContext.initClient(.{ .ca_file = ca_file, .tag = "fetch" }) orelse {
  497. err_out.* = "https is not available (no usable OpenSSL, or the caFile could not be loaded)";
  498. return null;
  499. };
  500. const key_copy = allocator.dupe(u8, key) catch {
  501. err_out.* = "out of memory";
  502. return null;
  503. };
  504. ctx_list.append(allocator, .{ .key = key_copy, .ctx = ctx }) catch {
  505. allocator.free(key_copy);
  506. err_out.* = "out of memory";
  507. return null;
  508. };
  509. return &ctx_list.items[ctx_list.items.len - 1].ctx;
  510. }
  511. // ── One HTTP exchange ────────────────────────────────────────────────────────
  512. const Exchange = struct {
  513. status: u16 = 0,
  514. headers: []Header = &.{},
  515. body: []u8 = &.{},
  516. fn deinit(self: *Exchange) void {
  517. freeHeaders(self.headers);
  518. allocator.free(self.body);
  519. }
  520. };
  521. fn headerValue(headers: []const Header, name: []const u8) ?[]const u8 {
  522. for (headers) |h| {
  523. if (std.ascii.eqlIgnoreCase(h.name, name)) return h.value;
  524. }
  525. return null;
  526. }
  527. fn hasHeader(headers: []const Header, name: []const u8) bool {
  528. return headerValue(headers, name) != null;
  529. }
  530. /// Send one request over one connection and read the whole response.
  531. /// `err_out` gets a short static reason; the caller adds the URL.
  532. /// The status code off a raw head, or null while unparseable.
  533. fn parseStatus(head: []const u8) ?u16 {
  534. var lines = std.mem.splitSequence(u8, head, "\r\n");
  535. const status_line = lines.next() orelse return null;
  536. var parts = std.mem.splitScalar(u8, status_line, ' ');
  537. _ = parts.next(); // HTTP/1.1
  538. const code = parts.next() orelse return null;
  539. return std.fmt.parseInt(u16, code, 10) catch null;
  540. }
  541. /// Head only → an Exchange with an EMPTY body (the chunks were the body).
  542. fn parseHeadOnly(head_raw: []const u8, err_out: *[]const u8) ?Exchange {
  543. // reuse the full parser on a synthetic complete response: the head as-is
  544. // (its transfer-encoding stripped so no body is expected) + no body.
  545. var synth: std.ArrayListUnmanaged(u8) = .empty;
  546. defer synth.deinit(allocator);
  547. var lines = std.mem.splitSequence(u8, head_raw[0 .. head_raw.len - 4], "\r\n");
  548. while (lines.next()) |line| {
  549. if (line.len > 18 and std.ascii.eqlIgnoreCase(line[0..18], "transfer-encoding:")) continue;
  550. if (line.len > 15 and std.ascii.eqlIgnoreCase(line[0..15], "content-length:")) continue;
  551. if (!add(&synth, line)) return oom(err_out);
  552. if (!add(&synth, "\r\n")) return oom(err_out);
  553. }
  554. if (!add(&synth, "\r\n")) return oom(err_out);
  555. return parseResponse(synth.items, err_out);
  556. }
  557. /// STREAM the body: post every decoded piece as a chunk frame until the peer
  558. /// closes (`connection: close` is on every request, so close IS the end).
  559. /// Chunked transfer is decoded incrementally; anything else streams as-is.
  560. fn streamBody(t: *Ticket, conn: *Conn, raw: *std.ArrayListUnmanaged(u8), he: usize, deadline: i64, err_out: *[]const u8) ?Exchange {
  561. defer raw.deinit(allocator);
  562. const chunked = blk: {
  563. if (findHeaderIn(raw.items[0..he], "transfer-encoding")) |v| {
  564. break :blk std.ascii.indexOfIgnoreCase(v, "chunked") != null;
  565. }
  566. break :blk false;
  567. };
  568. // chunked-decoder state, carried across reads
  569. var pending: std.ArrayListUnmanaged(u8) = .empty;
  570. defer pending.deinit(allocator);
  571. var remaining: usize = 0; // bytes left of the current chunk's data
  572. var done = false;
  573. // seed with whatever body bytes arrived along with the head
  574. if (raw.items.len > he) {
  575. pending.appendSlice(allocator, raw.items[he..]) catch return oom(err_out);
  576. }
  577. var buf: [16 * 1024]u8 = undefined;
  578. while (true) {
  579. // decode + post what we hold
  580. if (!chunked) {
  581. if (pending.items.len > 0) {
  582. postChunk(t, pending.items);
  583. pending.clearRetainingCapacity();
  584. }
  585. } else while (!done) {
  586. if (remaining > 0) {
  587. const take = @min(remaining, pending.items.len);
  588. if (take == 0) break;
  589. postChunk(t, pending.items[0..take]);
  590. std.mem.copyForwards(u8, pending.items, pending.items[take..]);
  591. pending.shrinkRetainingCapacity(pending.items.len - take);
  592. remaining -= take;
  593. if (remaining == 0) {
  594. // the CRLF after the chunk data
  595. if (pending.items.len < 2) break;
  596. std.mem.copyForwards(u8, pending.items, pending.items[2..]);
  597. pending.shrinkRetainingCapacity(pending.items.len - 2);
  598. }
  599. continue;
  600. }
  601. const nl = std.mem.indexOf(u8, pending.items, "\r\n") orelse break;
  602. const size_line = pending.items[0..nl];
  603. const semi = std.mem.indexOfScalar(u8, size_line, ';') orelse size_line.len;
  604. const n = std.fmt.parseInt(usize, std.mem.trim(u8, size_line[0..semi], " \t"), 16) catch {
  605. err_out.* = "the peer sent a malformed chunked body";
  606. return null;
  607. };
  608. std.mem.copyForwards(u8, pending.items, pending.items[nl + 2 ..]);
  609. pending.shrinkRetainingCapacity(pending.items.len - nl - 2);
  610. if (n == 0) {
  611. done = true;
  612. break;
  613. }
  614. remaining = n;
  615. }
  616. if (done) break;
  617. const n = conn.read(&buf);
  618. if (n == 0) break; // close IS the end (identity), or a truncated chunked stream
  619. if (n < 0) {
  620. if (nowMs() >= deadline) {
  621. err_out.* = "timed out";
  622. return null;
  623. }
  624. break;
  625. }
  626. pending.appendSlice(allocator, buf[0..@intCast(n)]) catch return oom(err_out);
  627. }
  628. return parseHeadOnly(raw.items[0..he], err_out);
  629. }
  630. fn exchange(t: *Ticket, url: Url, method: []const u8, body: []const u8, send_body: bool, deadline: i64, err_out: *[]const u8) ?Exchange {
  631. const fd = tcpConnect(url.host, url.port, deadline, err_out) orelse return null;
  632. if (!t.setLiveFd(fd)) {
  633. _ = c.close(fd);
  634. err_out.* = "aborted";
  635. return null;
  636. }
  637. var conn = Conn{ .fd = fd };
  638. if (url.https) {
  639. const ctx = clientCtx(t.req.ca_file, err_out) orelse {
  640. _ = c.close(fd);
  641. return null;
  642. };
  643. // 137's shared client half logs the specific failure itself; the caller
  644. // gets the located summary (certificate not trusted, or not a TLS server)
  645. const ssl = ctx.connect(fd, url.host, "fetch") orelse {
  646. _ = c.close(fd);
  647. err_out.* = "TLS handshake failed (certificate not trusted, or not a TLS server)";
  648. return null;
  649. };
  650. conn.ssl = ssl;
  651. conn.tls_ctx = ctx;
  652. }
  653. defer conn.close();
  654. defer t.clearLiveFd();
  655. // --- request ---
  656. var req_buf: std.ArrayListUnmanaged(u8) = .empty;
  657. defer req_buf.deinit(allocator);
  658. const default_port: u16 = if (url.https) 443 else 80;
  659. var ok = true;
  660. ok = ok and addFmt(&req_buf, "{s} {s} HTTP/1.1\r\n", .{ method, url.target });
  661. if (url.port == default_port) {
  662. ok = ok and addFmt(&req_buf, "host: {s}\r\n", .{url.host});
  663. } else {
  664. ok = ok and addFmt(&req_buf, "host: {s}:{d}\r\n", .{ url.host, url.port });
  665. }
  666. // `connection: close` on every request: there is no connection pool, and a
  667. // closed connection is also the unambiguous end of a body with no length.
  668. ok = ok and add(&req_buf, "connection: close\r\n");
  669. if (!hasHeader(t.req.headers, "user-agent")) {
  670. ok = ok and add(&req_buf, "user-agent: hybriel-fetch/1\r\n");
  671. }
  672. if (!hasHeader(t.req.headers, "accept")) {
  673. ok = ok and add(&req_buf, "accept: */*\r\n");
  674. }
  675. if (send_body) {
  676. ok = ok and addFmt(&req_buf, "content-length: {d}\r\n", .{body.len});
  677. if (t.req.json_body and !hasHeader(t.req.headers, "content-type")) {
  678. ok = ok and add(&req_buf, "content-type: application/json\r\n");
  679. }
  680. }
  681. for (t.req.headers) |h| {
  682. if (t.req.strip_credentials and sensitiveHeader(h.name)) continue;
  683. if (t.req.drop_body_headers and (std.ascii.eqlIgnoreCase(h.name, "content-type") or
  684. std.ascii.eqlIgnoreCase(h.name, "content-length"))) continue;
  685. // A caller header may not smuggle a second request in (CRLF injection).
  686. if (std.mem.indexOfAny(u8, h.name, "\r\n") != null or std.mem.indexOfAny(u8, h.value, "\r\n") != null) {
  687. err_out.* = "a header name or value contains a line break";
  688. return null;
  689. }
  690. ok = ok and addFmt(&req_buf, "{s}: {s}\r\n", .{ h.name, h.value });
  691. }
  692. ok = ok and add(&req_buf, "\r\n");
  693. if (send_body and body.len > 0) {
  694. ok = ok and add(&req_buf, body);
  695. }
  696. if (!ok) return oom(err_out);
  697. if (!conn.writeAll(req_buf.items)) {
  698. err_out.* = if (nowMs() >= deadline) "timed out" else "could not send the request";
  699. return null;
  700. }
  701. // --- response ---
  702. var raw: std.ArrayListUnmanaged(u8) = .empty;
  703. errdefer raw.deinit(allocator);
  704. var head_end: ?usize = null;
  705. var buf: [16 * 1024]u8 = undefined;
  706. while (true) {
  707. if (head_end == null) {
  708. if (std.mem.indexOf(u8, raw.items, "\r\n\r\n")) |idx| head_end = idx + 4;
  709. }
  710. if (head_end) |he| {
  711. // STREAMING (LLM tokens): the head is in — if this is the final
  712. // answer (not a redirect the caller follows), hand the rest of the
  713. // body over CHUNK BY CHUNK as it arrives instead of accumulating.
  714. if (t.req.stream) {
  715. const status_ok = parseStatus(raw.items[0..he]);
  716. if (status_ok != null and !isRedirect(status_ok.?)) {
  717. return streamBody(t, &conn, &raw, he, deadline, err_out);
  718. }
  719. }
  720. // Once the head is in, stop as soon as the body is provably complete.
  721. if (bodyComplete(raw.items, he)) break;
  722. }
  723. if (raw.items.len > MAX_BODY) {
  724. raw.deinit(allocator);
  725. err_out.* = "the response is larger than the 32 MiB limit";
  726. return null;
  727. }
  728. const n = conn.read(&buf);
  729. if (n == 0) break;
  730. if (n < 0) {
  731. if (nowMs() >= deadline) {
  732. raw.deinit(allocator);
  733. err_out.* = "timed out";
  734. return null;
  735. }
  736. // A TLS peer that just closes without close_notify, or a plain socket
  737. // reset after a complete answer: the parse below decides whether what
  738. // arrived is a whole response.
  739. break;
  740. }
  741. raw.appendSlice(allocator, buf[0..@intCast(n)]) catch {
  742. raw.deinit(allocator);
  743. return oom(err_out);
  744. };
  745. }
  746. const out = parseResponse(raw.items, err_out) orelse {
  747. raw.deinit(allocator);
  748. return null;
  749. };
  750. raw.deinit(allocator);
  751. return out;
  752. }
  753. fn add(buf: *std.ArrayListUnmanaged(u8), data: []const u8) bool {
  754. buf.appendSlice(allocator, data) catch return false;
  755. return true;
  756. }
  757. /// One request line or header, formatted. A header that does not fit 2 KiB is not
  758. /// a header anyone meant to send.
  759. fn addFmt(buf: *std.ArrayListUnmanaged(u8), comptime fmt: []const u8, args: anytype) bool {
  760. var tmp: [2048]u8 = undefined;
  761. const s = std.fmt.bufPrint(&tmp, fmt, args) catch return false;
  762. return add(buf, s);
  763. }
  764. fn oom(err_out: *[]const u8) ?Exchange {
  765. err_out.* = "out of memory";
  766. return null;
  767. }
  768. /// Is everything the response promised already in `raw`? Content-Length is exact,
  769. /// chunked ends at the zero chunk, and anything else ends when the peer closes.
  770. fn bodyComplete(raw: []const u8, head_end: usize) bool {
  771. const head = raw[0..head_end];
  772. if (findHeaderIn(head, "content-length")) |v| {
  773. const want = std.fmt.parseInt(usize, std.mem.trim(u8, v, " \t"), 10) catch return false;
  774. return raw.len - head_end >= want;
  775. }
  776. if (findHeaderIn(head, "transfer-encoding")) |v| {
  777. if (std.ascii.indexOfIgnoreCase(v, "chunked") != null) {
  778. return std.mem.indexOf(u8, raw[head_end..], "\r\n0\r\n") != null or
  779. std.mem.startsWith(u8, raw[head_end..], "0\r\n");
  780. }
  781. }
  782. return false;
  783. }
  784. fn findHeaderIn(head: []const u8, name: []const u8) ?[]const u8 {
  785. var lines = std.mem.splitSequence(u8, head, "\r\n");
  786. _ = lines.next(); // status line
  787. while (lines.next()) |line| {
  788. if (line.len == 0) break;
  789. const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;
  790. if (std.ascii.eqlIgnoreCase(std.mem.trim(u8, line[0..colon], " \t"), name)) {
  791. return std.mem.trim(u8, line[colon + 1 ..], " \t");
  792. }
  793. }
  794. return null;
  795. }
  796. fn parseResponse(raw: []const u8, err_out: *[]const u8) ?Exchange {
  797. const he = std.mem.indexOf(u8, raw, "\r\n\r\n") orelse {
  798. err_out.* = "the peer sent no complete HTTP response";
  799. return null;
  800. };
  801. const head = raw[0..he];
  802. const body_raw = raw[he + 4 ..];
  803. var lines = std.mem.splitSequence(u8, head, "\r\n");
  804. const status_line = lines.next() orelse {
  805. err_out.* = "the peer sent no status line";
  806. return null;
  807. };
  808. // "HTTP/1.1 200 OK"
  809. const sp = std.mem.indexOfScalar(u8, status_line, ' ') orelse {
  810. err_out.* = "the peer sent a malformed status line";
  811. return null;
  812. };
  813. const after = status_line[sp + 1 ..];
  814. const code_end = std.mem.indexOfScalar(u8, after, ' ') orelse after.len;
  815. const status = std.fmt.parseInt(u16, std.mem.trim(u8, after[0..code_end], " \t"), 10) catch {
  816. err_out.* = "the peer sent a malformed status line";
  817. return null;
  818. };
  819. var headers: std.ArrayListUnmanaged(Header) = .empty;
  820. errdefer {
  821. for (headers.items) |h| {
  822. allocator.free(h.name);
  823. allocator.free(h.value);
  824. }
  825. headers.deinit(allocator);
  826. }
  827. var chunked = false;
  828. while (lines.next()) |line| {
  829. if (line.len == 0) continue;
  830. const colon = std.mem.indexOfScalar(u8, line, ':') orelse continue;
  831. const name = std.mem.trim(u8, line[0..colon], " \t");
  832. const value = std.mem.trim(u8, line[colon + 1 ..], " \t");
  833. if (name.len == 0) continue;
  834. const name_copy = allocator.dupe(u8, name) catch return oom(err_out);
  835. http.toLowercase(name_copy);
  836. const value_copy = allocator.dupe(u8, value) catch {
  837. allocator.free(name_copy);
  838. return oom(err_out);
  839. };
  840. if (std.mem.eql(u8, name_copy, "transfer-encoding") and
  841. std.ascii.indexOfIgnoreCase(value_copy, "chunked") != null) chunked = true;
  842. headers.append(allocator, .{ .name = name_copy, .value = value_copy }) catch {
  843. allocator.free(name_copy);
  844. allocator.free(value_copy);
  845. return oom(err_out);
  846. };
  847. }
  848. var body: []u8 = undefined;
  849. if (chunked) {
  850. body = dechunk(body_raw) orelse {
  851. for (headers.items) |h| {
  852. allocator.free(h.name);
  853. allocator.free(h.value);
  854. }
  855. headers.deinit(allocator);
  856. err_out.* = "the peer sent a malformed chunked body";
  857. return null;
  858. };
  859. } else if (findHeaderIn(head, "content-length")) |v| {
  860. const want = std.fmt.parseInt(usize, v, 10) catch body_raw.len;
  861. const take = @min(want, body_raw.len);
  862. body = allocator.dupe(u8, body_raw[0..take]) catch return oom(err_out);
  863. } else {
  864. body = allocator.dupe(u8, body_raw) catch return oom(err_out);
  865. }
  866. const headers_slice = headers.toOwnedSlice(allocator) catch return oom(err_out);
  867. return .{ .status = status, .headers = headers_slice, .body = body };
  868. }
  869. fn dechunk(input: []const u8) ?[]u8 {
  870. var out: std.ArrayListUnmanaged(u8) = .empty;
  871. var i: usize = 0;
  872. while (true) {
  873. const line_end = std.mem.indexOfPos(u8, input, i, "\r\n") orelse {
  874. out.deinit(allocator);
  875. return null;
  876. };
  877. var size_txt = input[i..line_end];
  878. if (std.mem.indexOfScalar(u8, size_txt, ';')) |semi| size_txt = size_txt[0..semi];
  879. const size = std.fmt.parseInt(usize, std.mem.trim(u8, size_txt, " \t"), 16) catch {
  880. out.deinit(allocator);
  881. return null;
  882. };
  883. i = line_end + 2;
  884. if (size == 0) return out.toOwnedSlice(allocator) catch null;
  885. if (i + size > input.len) {
  886. out.deinit(allocator);
  887. return null;
  888. }
  889. out.appendSlice(allocator, input[i .. i + size]) catch {
  890. out.deinit(allocator);
  891. return null;
  892. };
  893. i += size + 2; // skip the chunk's trailing CRLF
  894. if (i > input.len) return out.toOwnedSlice(allocator) catch null;
  895. }
  896. }
  897. // ── The worker: one thread per fetch, redirects and all ───────────────────────
  898. fn isRedirect(status: u16) bool {
  899. return status == 301 or status == 302 or status == 303 or status == 307 or status == 308;
  900. }
  901. // ── The ACTIVE registry: every in-flight ticket, so `fetchAbort(tag)` can find
  902. // its socket. Added at spawn, removed at finish — a finished ticket is owned by
  903. // its handle alone and an abort of it is a no-op.
  904. var active_mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER;
  905. var active_tickets: std.ArrayListUnmanaged(*Ticket) = .empty;
  906. fn activeAdd(t: *Ticket) void {
  907. mutexLock(&active_mutex);
  908. active_tickets.append(allocator, t) catch {};
  909. mutexUnlock(&active_mutex);
  910. }
  911. fn activeRemove(t: *Ticket) void {
  912. mutexLock(&active_mutex);
  913. for (active_tickets.items, 0..) |a, i| {
  914. if (a == t) {
  915. _ = active_tickets.swapRemove(i);
  916. break;
  917. }
  918. }
  919. mutexUnlock(&active_mutex);
  920. }
  921. fn workerMain(t: *Ticket) void {
  922. runFetch(t);
  923. activeRemove(t);
  924. // an aborted request reports ABORTED whatever the read error looked like —
  925. // the app asked for the interrupt, the message says the interrupt happened
  926. if (t.aborted) {
  927. if (t.err) |e| allocator.free(e);
  928. t.err = std.fmt.allocPrint(allocator, "hl:fetch: aborted", .{}) catch null;
  929. }
  930. t.finish();
  931. postCompletion(t);
  932. }
  933. fn runFetch(t: *Ticket) void {
  934. const deadline = nowMs() + t.req.timeout_ms;
  935. var current = allocator.dupe(u8, t.req.url) catch {
  936. t.fail("hl:fetch: out of memory", .{});
  937. return;
  938. };
  939. var method = allocator.dupe(u8, t.req.method) catch {
  940. allocator.free(current);
  941. t.fail("hl:fetch: out of memory", .{});
  942. return;
  943. };
  944. var send_body = t.req.has_body;
  945. var hops: u32 = 0;
  946. while (true) {
  947. const url = parseUrl(current) orelse {
  948. t.fail("hl:fetch: '{s}' is not an http:// or https:// URL", .{current});
  949. allocator.free(current);
  950. allocator.free(method);
  951. return;
  952. };
  953. var reason: []const u8 = "connection failed";
  954. var ex = exchange(t, url, method, t.req.body, send_body, deadline, &reason) orelse {
  955. t.fail("hl:fetch {s} {s}: {s}", .{ method, current, reason });
  956. allocator.free(current);
  957. allocator.free(method);
  958. return;
  959. };
  960. if (isRedirect(ex.status) and hops < t.req.max_redirects) {
  961. if (headerValue(ex.headers, "location")) |loc| {
  962. const next = resolveLocation(current, loc) orelse {
  963. t.fail("hl:fetch {s}: redirect to an unusable Location '{s}'", .{ current, loc });
  964. ex.deinit();
  965. allocator.free(current);
  966. allocator.free(method);
  967. return;
  968. };
  969. const next_url = parseUrl(next) orelse {
  970. t.fail("hl:fetch: unusable redirect URL", .{});
  971. allocator.free(next);
  972. ex.deinit();
  973. allocator.free(current);
  974. allocator.free(method);
  975. return;
  976. };
  977. // Once stripped, credentials stay stripped even if a later hop returns.
  978. if (!sameOrigin(url, next_url)) t.req.strip_credentials = true;
  979. // 303 always becomes a GET; 301/302 become one for anything that
  980. // is not already GET/HEAD — what every browser does, and what a
  981. // server that answers a POST with "see the result over there"
  982. // means. 307/308 keep the method AND the body by definition.
  983. if (ex.status == 303 or
  984. ((ex.status == 301 or ex.status == 302) and
  985. !std.mem.eql(u8, method, "GET") and !std.mem.eql(u8, method, "HEAD")))
  986. {
  987. allocator.free(method);
  988. method = allocator.dupe(u8, "GET") catch {
  989. allocator.free(next);
  990. ex.deinit();
  991. allocator.free(current);
  992. t.fail("hl:fetch: out of memory", .{});
  993. return;
  994. };
  995. send_body = false;
  996. t.req.drop_body_headers = true;
  997. }
  998. ex.deinit();
  999. allocator.free(current);
  1000. current = next;
  1001. hops += 1;
  1002. continue;
  1003. }
  1004. }
  1005. if (isRedirect(ex.status) and t.req.max_redirects > 0 and hops >= t.req.max_redirects) {
  1006. t.fail("hl:fetch {s}: more than {d} redirects", .{ t.req.url, t.req.max_redirects });
  1007. ex.deinit();
  1008. allocator.free(current);
  1009. allocator.free(method);
  1010. return;
  1011. }
  1012. t.status = ex.status;
  1013. t.headers = ex.headers;
  1014. t.body = ex.body;
  1015. t.final_url = current;
  1016. allocator.free(method);
  1017. return;
  1018. }
  1019. }
  1020. // ── The value shapes handed back to Hybriel ──────────────────────────────────
  1021. fn hlStr(s: []const u8) api.HlString {
  1022. return .{ .ptr = s.ptr, .len = s.len };
  1023. }
  1024. /// Only the SHELLS are freed: every string in a `result()` object points into the
  1025. /// ticket, which outlives the call (the loader copies what it keeps before this
  1026. /// runs — the plugin ABI's ownership rule).
  1027. fn respShellDeinit(obj: *HlObject) callconv(.c) void {
  1028. const hdrs = if (obj.field_count > 3) obj.fields[3].value else api.makeNull();
  1029. if (hdrs.type == .hl_object) {
  1030. const inner = hdrs.data.object;
  1031. allocator.free(inner.fields[0..inner.field_count]);
  1032. allocator.destroy(inner);
  1033. }
  1034. allocator.free(obj.fields[0..obj.field_count]);
  1035. allocator.destroy(obj);
  1036. }
  1037. fn buildHeadersObject(headers: []const Header) ?*HlObject {
  1038. const fields = allocator.alloc(HlField, headers.len) catch return null;
  1039. for (headers, 0..) |h, i| {
  1040. fields[i] = .{ .key = hlStr(h.name), .value = api.makeString(h.value) };
  1041. }
  1042. const obj = allocator.create(HlObject) catch {
  1043. allocator.free(fields);
  1044. return null;
  1045. };
  1046. obj.* = .{ .fields = fields.ptr, .field_count = headers.len, .deinit_fn = null };
  1047. return obj;
  1048. }
  1049. /// `{ status, ok, url, headers, body, tag }` — the response as the .hl side sees
  1050. /// it, hydrated into a FetchResponse by server.hl.
  1051. fn buildResponse(t: *Ticket) HlValue {
  1052. const headers_obj = buildHeadersObject(t.headers) orelse return api.makeError("hl:fetch: out of memory");
  1053. const fields = allocator.alloc(HlField, 6) catch {
  1054. allocator.free(headers_obj.fields[0..headers_obj.field_count]);
  1055. allocator.destroy(headers_obj);
  1056. return api.makeError("hl:fetch: out of memory");
  1057. };
  1058. fields[0] = .{ .key = hlStr("status"), .value = api.makeNumber(@floatFromInt(t.status)) };
  1059. fields[1] = .{ .key = hlStr("ok"), .value = api.makeBool(t.status >= 200 and t.status < 300) };
  1060. fields[2] = .{ .key = hlStr("url"), .value = api.makeString(t.final_url) };
  1061. fields[3] = .{ .key = hlStr("headers"), .value = api.makeObject(headers_obj) };
  1062. fields[4] = .{ .key = hlStr("body"), .value = api.makeString(t.body) };
  1063. fields[5] = .{ .key = hlStr("tag"), .value = api.makeString(t.req.tag) };
  1064. const obj = allocator.create(HlObject) catch {
  1065. allocator.free(fields);
  1066. allocator.free(headers_obj.fields[0..headers_obj.field_count]);
  1067. allocator.destroy(headers_obj);
  1068. return api.makeError("hl:fetch: out of memory");
  1069. };
  1070. obj.* = .{ .fields = fields.ptr, .field_count = 6, .deinit_fn = &respShellDeinit };
  1071. return api.makeObject(obj);
  1072. }
  1073. // ── The ticket handle ────────────────────────────────────────────────────────
  1074. fn ticketCall(ctx: ?*anyopaque, op: api.HlString, argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1075. _ = argc;
  1076. _ = argv;
  1077. const t: *Ticket = @ptrCast(@alignCast(ctx orelse return api.makeError("hl:fetch: dead ticket")));
  1078. const name = op.ptr[0..op.len];
  1079. if (std.mem.eql(u8, name, "done")) {
  1080. return api.makeBool(t.isDone());
  1081. }
  1082. if (std.mem.eql(u8, name, "doneFd")) {
  1083. return api.makeNumber(@floatFromInt(t.doneFd()));
  1084. }
  1085. if (std.mem.eql(u8, name, "tryResult")) {
  1086. t.wait();
  1087. if (t.err) |msg| {
  1088. const fields = allocator.alloc(HlField, 3) catch return api.makeError("hl:fetch: out of memory");
  1089. const obj = allocator.create(HlObject) catch {
  1090. allocator.free(fields);
  1091. return api.makeError("hl:fetch: out of memory");
  1092. };
  1093. fields[0] = .{ .key = hlStr("ok"), .value = api.makeBool(false) };
  1094. fields[1] = .{ .key = hlStr("status"), .value = api.makeNumber(0) };
  1095. fields[2] = .{ .key = hlStr("error"), .value = api.makeString(msg) };
  1096. obj.* = .{ .fields = fields.ptr, .field_count = 3, .deinit_fn = &respShellDeinit };
  1097. return api.makeObject(obj);
  1098. }
  1099. return buildResponse(t);
  1100. }
  1101. if (std.mem.eql(u8, name, "result")) {
  1102. t.wait();
  1103. if (t.err) |msg| return api.makeError(msg);
  1104. return buildResponse(t);
  1105. }
  1106. if (std.mem.eql(u8, name, "events")) {
  1107. if (t.ev_wake_fd < 0) return api.makeError("hl:fetch: events() is stream mode — start the fetch with stream = true");
  1108. const iter = allocator.create(HlIterator) catch return api.makeError("hl:fetch: out of memory");
  1109. iter.* = .{
  1110. .context = @ptrCast(t),
  1111. .next_fn = &eventsTryNext, // non-blocking either way — event loop only
  1112. .deinit_fn = null,
  1113. .try_next_fn = &eventsTryNext,
  1114. .wake_fd = t.ev_wake_fd,
  1115. };
  1116. return api.makeIterator(iter);
  1117. }
  1118. if (std.mem.eql(u8, name, "abort")) {
  1119. t.abort();
  1120. return api.makeBool(true);
  1121. }
  1122. return api.makeError("hl:fetch: a pending fetch has no method by that name");
  1123. }
  1124. fn ticketClose(ctx: ?*anyopaque) callconv(.c) void {
  1125. const t: *Ticket = @ptrCast(@alignCast(ctx orelse return));
  1126. // The worker writes into this ticket, so it is JOINED before anything is
  1127. // freed — a detached thread finishing after the free is a use-after-free the
  1128. // collector would surface as random corruption. A dropped, never-read fetch
  1129. // therefore costs at most its own timeout at collection time.
  1130. if (t.thread) |th| {
  1131. th.join();
  1132. t.thread = null;
  1133. }
  1134. t.req.deinit();
  1135. if (t.done_fd >= 0) _ = std.os.linux.close(t.done_fd);
  1136. // The stream bell (stream = true) is the ticket's own too: without this every streamed fetch leaked one eventfd (#efd439, hycon EMFILE).
  1137. if (t.ev_wake_fd >= 0) {
  1138. _ = std.os.linux.close(t.ev_wake_fd);
  1139. t.ev_wake_fd = -1;
  1140. }
  1141. for (t.ev_queue.items) |comp| {
  1142. allocator.free(comp.tag);
  1143. allocator.free(comp.url);
  1144. allocator.free(comp.body);
  1145. allocator.free(comp.err);
  1146. if (comp.chunk) |ch| allocator.free(ch);
  1147. for (comp.headers) |h| {
  1148. allocator.free(h.name);
  1149. allocator.free(h.value);
  1150. }
  1151. if (comp.headers.len > 0) allocator.free(comp.headers);
  1152. }
  1153. t.ev_queue.deinit(allocator);
  1154. freeHeaders(t.headers);
  1155. allocator.free(t.body);
  1156. allocator.free(t.final_url);
  1157. if (t.err) |e| allocator.free(e);
  1158. allocator.destroy(t);
  1159. }
  1160. // ── Argument reading ─────────────────────────────────────────────────────────
  1161. fn fieldOf(v: HlValue, name: []const u8) ?HlValue {
  1162. if (v.type != .hl_object) return null;
  1163. const obj = v.data.object;
  1164. for (obj.fields[0..obj.field_count]) |f| {
  1165. if (std.mem.eql(u8, f.key.ptr[0..f.key.len], name)) return f.value;
  1166. }
  1167. return null;
  1168. }
  1169. fn dupString(v: ?HlValue, fallback: []const u8) []u8 {
  1170. if (v) |val| {
  1171. if (val.type == .hl_string) {
  1172. return allocator.dupe(u8, val.data.string.ptr[0..val.data.string.len]) catch
  1173. allocator.dupe(u8, fallback) catch unreachable;
  1174. }
  1175. }
  1176. return allocator.dupe(u8, fallback) catch unreachable;
  1177. }
  1178. fn numberOr(v: ?HlValue, fallback: i64) i64 {
  1179. if (v) |val| {
  1180. if (val.type == .hl_number) return @intFromFloat(val.data.number);
  1181. }
  1182. return fallback;
  1183. }
  1184. fn boolOr(v: ?HlValue, fallback: bool) bool {
  1185. if (v) |val| {
  1186. if (val.type == .hl_bool) return val.data.boolean;
  1187. }
  1188. return fallback;
  1189. }
  1190. fn readHeaders(v: ?HlValue) []Header {
  1191. const val = v orelse return &.{};
  1192. if (val.type != .hl_object) return &.{};
  1193. const obj = val.data.object;
  1194. var list: std.ArrayListUnmanaged(Header) = .empty;
  1195. for (obj.fields[0..obj.field_count]) |f| {
  1196. if (f.value.type != .hl_string) continue;
  1197. const name = allocator.dupe(u8, f.key.ptr[0..f.key.len]) catch continue;
  1198. const value = allocator.dupe(u8, f.value.data.string.ptr[0..f.value.data.string.len]) catch {
  1199. allocator.free(name);
  1200. continue;
  1201. };
  1202. list.append(allocator, .{ .name = name, .value = value }) catch {
  1203. allocator.free(name);
  1204. allocator.free(value);
  1205. };
  1206. }
  1207. return list.toOwnedSlice(allocator) catch &.{};
  1208. }
  1209. fn decodeBodyHex(hex: []const u8) ![]u8 {
  1210. if (hex.len % 2 != 0) return error.InvalidHex;
  1211. const body = try allocator.alloc(u8, hex.len / 2);
  1212. errdefer allocator.free(body);
  1213. _ = try std.fmt.hexToBytes(body, hex);
  1214. return body;
  1215. }
  1216. test "Bytes request bodies decode exactly including invalid UTF-8" {
  1217. const body = try decodeBodyHex("0080ff41c328");
  1218. defer allocator.free(body);
  1219. try std.testing.expectEqualSlices(u8, &.{ 0, 128, 255, 65, 195, 40 }, body);
  1220. const empty = try decodeBodyHex("");
  1221. defer allocator.free(empty);
  1222. try std.testing.expectEqual(@as(usize, 0), empty.len);
  1223. try std.testing.expectError(error.InvalidHex, decodeBodyHex("0"));
  1224. try std.testing.expectError(error.InvalidCharacter, decodeBodyHex("zz"));
  1225. }
  1226. /// __native("fetch.start", url, options) → a ticket HANDLE, immediately.
  1227. /// Options: method, headers, body, jsonBody, timeoutMs, maxRedirects, caFile, tag.
  1228. export fn hl_fetch_start(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1229. if (argc < 1 or argv[0].type != .hl_string) {
  1230. return api.makeError("hl:fetch: fetch() needs a URL string");
  1231. }
  1232. const url = argv[0].data.string.ptr[0..argv[0].data.string.len];
  1233. const opts: ?HlValue = if (argc > 1 and argv[1].type == .hl_object) argv[1] else null;
  1234. // Bytes cross the ABI as hex in argv[2], following hl:fs / hl:crypto.
  1235. const bv = if (opts) |o| fieldOf(o, "body") else null;
  1236. if (bv) |v| {
  1237. if (v.type != .hl_null and v.type != .hl_string)
  1238. return api.makeError("hl:fetch: body must be a String or Bytes (use json for JSON)");
  1239. }
  1240. const hex = if (argc > 2 and argv[2].type == .hl_string) argv[2].data.string else null;
  1241. const body = if (hex) |h| decodeBodyHex(h.ptr[0..h.len]) catch
  1242. return api.makeError("hl:fetch: invalid Bytes body or out of memory")
  1243. else dupString(bv, "");
  1244. const has_body = hex != null or (bv != null and bv.?.type == .hl_string);
  1245. const method_raw = dupString(if (opts) |o| fieldOf(o, "method") else null, "GET");
  1246. for (method_raw) |*ch| {
  1247. if (ch.* >= 'a' and ch.* <= 'z') ch.* -= 32;
  1248. }
  1249. const ca_val = if (opts) |o| fieldOf(o, "caFile") else null;
  1250. const ca_file: ?[]u8 = if (ca_val != null and ca_val.?.type == .hl_string)
  1251. allocator.dupe(u8, ca_val.?.data.string.ptr[0..ca_val.?.data.string.len]) catch null
  1252. else
  1253. null;
  1254. const t = allocator.create(Ticket) catch return api.makeError("hl:fetch: out of memory");
  1255. t.* = .{
  1256. .req = .{
  1257. .method = method_raw,
  1258. .url = allocator.dupe(u8, url) catch return api.makeError("hl:fetch: out of memory"),
  1259. .headers = readHeaders(if (opts) |o| fieldOf(o, "headers") else null),
  1260. .body = body,
  1261. .has_body = has_body,
  1262. .json_body = boolOr(if (opts) |o| fieldOf(o, "jsonBody") else null, false),
  1263. .timeout_ms = @max(numberOr(if (opts) |o| fieldOf(o, "timeoutMs") else null, DEFAULT_TIMEOUT_MS), 1),
  1264. .max_redirects = @intCast(@max(numberOr(if (opts) |o| fieldOf(o, "maxRedirects") else null, DEFAULT_MAX_REDIRECTS), 0)),
  1265. .ca_file = ca_file,
  1266. .tag = dupString(if (opts) |o| fieldOf(o, "tag") else null, ""),
  1267. .stream = boolOr(if (opts) |o| fieldOf(o, "stream") else null, false),
  1268. },
  1269. };
  1270. if (t.req.stream) t.ev_wake_fd = http.makeWakeFd();
  1271. activeAdd(t);
  1272. t.thread = std.Thread.spawn(.{}, workerMain, .{t}) catch {
  1273. // No thread: run it here rather than lying about having started. The call
  1274. // then blocks, which is slower and still correct.
  1275. workerMain(t);
  1276. t.thread = null;
  1277. return makeTicketHandle(t);
  1278. };
  1279. return makeTicketHandle(t);
  1280. }
  1281. fn makeTicketHandle(t: *Ticket) HlValue {
  1282. const h = allocator.create(HlHandle) catch return api.makeError("hl:fetch: out of memory");
  1283. h.* = .{
  1284. .context = @ptrCast(t),
  1285. .call_fn = &ticketCall,
  1286. .close_fn = &ticketClose,
  1287. .type_name = hlStr("pending fetch"),
  1288. };
  1289. return api.makeHandle(h);
  1290. }
  1291. // ── The completions source: a loop source with the mission-125 bell ──────────
  1292. //
  1293. // `for (ev of completions())` / `eventloop.register` — the SAME shape hl:http1's
  1294. // request and ws-event sources have, so a finished fetch reaches an `on fetched(ev)`
  1295. // handler through the loop's own `epoll_wait` instead of anyone polling. The queue
  1296. // is filled by the worker threads and drained by the loop thread.
  1297. const Completion = struct {
  1298. aborted: bool = false,
  1299. tag: []u8,
  1300. url: []u8,
  1301. status: u16,
  1302. headers: []Header,
  1303. body: []u8,
  1304. err: []u8,
  1305. /// non-null = a STREAM CHUNK frame ({tag, url, chunk}), not a completion
  1306. chunk: ?[]u8 = null,
  1307. };
  1308. var comp_mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER;
  1309. var comp_queue: std.ArrayListUnmanaged(Completion) = .empty;
  1310. var comp_wake_fd: i32 = -1;
  1311. var comp_enabled = std.atomic.Value(bool).init(false);
  1312. /// Called by every worker as its last act. Nothing is copied — and no wake is
  1313. /// rung — unless a completions source actually exists, so a program that only
  1314. /// uses `result()` pays nothing for this.
  1315. /// One decoded piece of a STREAMING body → a `{ tag, url, chunk }` frame on the
  1316. /// completions source, bell rung. Dropped (with one log line) when no source is
  1317. /// armed — a stream nobody listens to is a programming error worth seeing.
  1318. fn postChunk(t: *Ticket, bytes: []const u8) void {
  1319. if (t.ev_wake_fd < 0 and !comp_enabled.load(.acquire)) {
  1320. logMsg("hl:fetch: stream chunk dropped — nobody is listening");
  1321. return;
  1322. }
  1323. const comp = Completion{
  1324. .tag = allocator.dupe(u8, t.req.tag) catch return,
  1325. .url = allocator.dupe(u8, t.req.url) catch return,
  1326. .status = 0,
  1327. .headers = &.{},
  1328. .body = allocator.dupe(u8, "") catch return,
  1329. .err = allocator.dupe(u8, "") catch return,
  1330. .chunk = allocator.dupe(u8, bytes) catch return,
  1331. };
  1332. postFrame(t, comp);
  1333. }
  1334. /// One frame to wherever this ticket's listener lives: the ticket's own source
  1335. /// (stream mode) or the global completions source.
  1336. fn postFrame(t: *Ticket, comp: Completion) void {
  1337. if (t.ev_wake_fd >= 0) {
  1338. mutexLock(&t.mutex);
  1339. t.ev_queue.append(allocator, comp) catch {};
  1340. mutexUnlock(&t.mutex);
  1341. http.ringWake(t.ev_wake_fd);
  1342. return;
  1343. }
  1344. mutexLock(&comp_mutex);
  1345. comp_queue.append(allocator, comp) catch {};
  1346. mutexUnlock(&comp_mutex);
  1347. http.ringWake(comp_wake_fd);
  1348. }
  1349. fn postCompletion(t: *Ticket) void {
  1350. if (t.ev_wake_fd < 0 and !comp_enabled.load(.acquire)) return;
  1351. var headers = allocator.alloc(Header, t.headers.len) catch return;
  1352. var built: usize = 0;
  1353. for (t.headers, 0..) |h, i| {
  1354. const n = allocator.dupe(u8, h.name) catch break;
  1355. const v = allocator.dupe(u8, h.value) catch {
  1356. allocator.free(n);
  1357. break;
  1358. };
  1359. headers[i] = .{ .name = n, .value = v };
  1360. built = i + 1;
  1361. }
  1362. headers = headers[0..built];
  1363. const comp = Completion{
  1364. .aborted = t.aborted,
  1365. .tag = allocator.dupe(u8, t.req.tag) catch "",
  1366. .url = allocator.dupe(u8, if (t.final_url.len > 0) t.final_url else t.req.url) catch "",
  1367. .status = t.status,
  1368. .headers = headers,
  1369. .body = allocator.dupe(u8, t.body) catch "",
  1370. .err = allocator.dupe(u8, if (t.err) |e| e else "") catch "",
  1371. };
  1372. // Ring generously (D-125): the loop treats the fd as a bell, so a wake for a
  1373. // queue somebody already drained costs one empty round and nothing else.
  1374. postFrame(t, comp);
  1375. }
  1376. /// Frees the SHELLS and the payload: a completion is a snapshot nobody else owns.
  1377. fn compObjDeinit(obj: *HlObject) callconv(.c) void {
  1378. const fields = obj.fields[0..obj.field_count];
  1379. for (fields) |f| {
  1380. if (f.value.type == .hl_string) {
  1381. const s = f.value.data.string;
  1382. if (s.len > 0) allocator.free(@constCast(s.ptr[0..s.len]));
  1383. } else if (f.value.type == .hl_object) {
  1384. const inner = f.value.data.object;
  1385. for (inner.fields[0..inner.field_count]) |hf| {
  1386. allocator.free(@constCast(hf.key.ptr[0..hf.key.len]));
  1387. const hv = hf.value.data.string;
  1388. allocator.free(@constCast(hv.ptr[0..hv.len]));
  1389. }
  1390. allocator.free(inner.fields[0..inner.field_count]);
  1391. allocator.destroy(inner);
  1392. }
  1393. }
  1394. allocator.free(fields);
  1395. allocator.destroy(obj);
  1396. }
  1397. fn completionsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  1398. _ = ctx;
  1399. mutexLock(&comp_mutex);
  1400. if (comp_queue.items.len == 0) {
  1401. mutexUnlock(&comp_mutex);
  1402. return api.makeNull();
  1403. }
  1404. const comp = comp_queue.orderedRemove(0);
  1405. if (comp_queue.items.len > 0) http.ringWake(comp_wake_fd);
  1406. mutexUnlock(&comp_mutex);
  1407. return frameToValue(comp);
  1408. }
  1409. /// A streaming ticket's own source: drains that ticket's queue and nothing else.
  1410. fn eventsTryNext(ctx: ?*anyopaque) callconv(.c) HlValue {
  1411. const t: *Ticket = @ptrCast(@alignCast(ctx orelse return api.makeNull()));
  1412. mutexLock(&t.mutex);
  1413. if (t.ev_queue.items.len == 0) {
  1414. mutexUnlock(&t.mutex);
  1415. return api.makeNull();
  1416. }
  1417. const comp = t.ev_queue.orderedRemove(0);
  1418. if (t.ev_queue.items.len > 0) http.ringWake(t.ev_wake_fd);
  1419. mutexUnlock(&t.mutex);
  1420. return frameToValue(comp);
  1421. }
  1422. fn frameToValue(comp: Completion) HlValue {
  1423. // a STREAM CHUNK frame: { tag, url, chunk } and nothing else
  1424. if (comp.chunk) |chunk| {
  1425. allocator.free(comp.body);
  1426. allocator.free(comp.err);
  1427. const cfields = allocator.alloc(HlField, 3) catch return api.makeNull();
  1428. cfields[0] = .{ .key = hlStr("tag"), .value = api.makeString(comp.tag) };
  1429. cfields[1] = .{ .key = hlStr("url"), .value = api.makeString(comp.url) };
  1430. cfields[2] = .{ .key = hlStr("chunk"), .value = api.makeString(chunk) };
  1431. const cobj = allocator.create(HlObject) catch {
  1432. allocator.free(cfields);
  1433. return api.makeNull();
  1434. };
  1435. cobj.* = .{ .fields = cfields.ptr, .field_count = 3, .deinit_fn = &compObjDeinit };
  1436. return api.makeObject(cobj);
  1437. }
  1438. const hdr_fields = allocator.alloc(HlField, comp.headers.len) catch return api.makeNull();
  1439. for (comp.headers, 0..) |h, i| {
  1440. hdr_fields[i] = .{ .key = hlStr(h.name), .value = api.makeString(h.value) };
  1441. }
  1442. const hdr_obj = allocator.create(HlObject) catch {
  1443. allocator.free(hdr_fields);
  1444. return api.makeNull();
  1445. };
  1446. hdr_obj.* = .{ .fields = hdr_fields.ptr, .field_count = comp.headers.len, .deinit_fn = null };
  1447. allocator.free(comp.headers);
  1448. const fields = allocator.alloc(HlField, 8) catch return api.makeNull();
  1449. fields[0] = .{ .key = hlStr("tag"), .value = api.makeString(comp.tag) };
  1450. fields[1] = .{ .key = hlStr("url"), .value = api.makeString(comp.url) };
  1451. fields[2] = .{ .key = hlStr("status"), .value = api.makeNumber(@floatFromInt(comp.status)) };
  1452. fields[3] = .{ .key = hlStr("ok"), .value = api.makeBool(comp.status >= 200 and comp.status < 300) };
  1453. fields[4] = .{ .key = hlStr("body"), .value = api.makeString(comp.body) };
  1454. fields[5] = .{ .key = hlStr("error"), .value = api.makeString(comp.err) };
  1455. fields[6] = .{ .key = hlStr("headers"), .value = api.makeObject(hdr_obj) };
  1456. fields[7] = .{ .key = hlStr("aborted"), .value = api.makeBool(comp.aborted) };
  1457. const obj = allocator.create(HlObject) catch {
  1458. allocator.free(fields);
  1459. return api.makeNull();
  1460. };
  1461. obj.* = .{ .fields = fields.ptr, .field_count = 8, .deinit_fn = &compObjDeinit };
  1462. return api.makeObject(obj);
  1463. }
  1464. /// __native("fetch.abort", tag) — THE INTERRUPT (the LLM stop button): every
  1465. /// in-flight fetch whose `tag` matches is aborted by shutting its socket down.
  1466. /// The peer sees the disconnect (llama-server / OpenRouter stop generating and
  1467. /// billing), the worker's read unblocks, and the FINAL completion frame arrives
  1468. /// with `aborted = true` and error "hl:fetch: aborted". Returns how many were
  1469. /// aborted (0 = nothing in flight under that tag — already finished, or a typo).
  1470. export fn hl_fetch_abort(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1471. if (argc < 1 or argv[0].type != .hl_string) {
  1472. return api.makeError("hl:fetch abort: pass the tag the fetch was started with");
  1473. }
  1474. const tag = argv[0].data.string.ptr[0..argv[0].data.string.len];
  1475. var n: u32 = 0;
  1476. mutexLock(&active_mutex);
  1477. for (active_tickets.items) |t| {
  1478. if (std.mem.eql(u8, t.req.tag, tag)) {
  1479. t.abort();
  1480. n += 1;
  1481. }
  1482. }
  1483. mutexUnlock(&active_mutex);
  1484. return api.makeNumber(@floatFromInt(n));
  1485. }
  1486. /// __native("fetch.completions") → the loop source. Calling it ARMS completion
  1487. /// delivery for every fetch started from here on.
  1488. export fn hl_fetch_completions(argc: u32, argv: [*]const HlValue) callconv(.c) HlValue {
  1489. _ = argc;
  1490. _ = argv;
  1491. mutexLock(&comp_mutex);
  1492. if (comp_wake_fd < 0) comp_wake_fd = http.makeWakeFd();
  1493. mutexUnlock(&comp_mutex);
  1494. comp_enabled.store(true, .release);
  1495. const iter = allocator.create(HlIterator) catch return api.makeError("hl:fetch: out of memory");
  1496. iter.* = .{
  1497. .context = null,
  1498. .next_fn = &completionsTryNext, // non-blocking either way — event loop only
  1499. .deinit_fn = null,
  1500. .try_next_fn = &completionsTryNext,
  1501. .wake_fd = comp_wake_fd,
  1502. };
  1503. return api.makeIterator(iter);
  1504. }
  1505. test "wake burst fetch stream and global completions" {
  1506. const w = @import("wake_test");
  1507. var stream_passed: usize = 0;
  1508. var global_passed: usize = 0;
  1509. for (0..10) |_| {
  1510. comp_wake_fd = w.bell();
  1511. defer _ = linux.close(comp_wake_fd);
  1512. defer comp_queue.deinit(allocator);
  1513. comp_queue = .empty;
  1514. var t: Ticket = undefined;
  1515. t.mutex = libc.PTHREAD_MUTEX_INITIALIZER;
  1516. t.ev_queue = .empty;
  1517. const stream_fd = w.bell();
  1518. t.ev_wake_fd = stream_fd;
  1519. defer _ = linux.close(stream_fd);
  1520. defer t.ev_queue.deinit(allocator);
  1521. for (0..2) |mode| {
  1522. if (mode == 1) t.ev_wake_fd = -1;
  1523. for (0..221) |i| postFrame(&t, .{
  1524. .tag = @constCast(""), .url = @constCast(""), .status = 200,
  1525. .headers = &.{}, .body = @constCast(""), .err = @constCast(""),
  1526. .chunk = if (i < 220) try allocator.dupe(u8, "chunk") else null,
  1527. });
  1528. if (mode == 0) {
  1529. if (w.burst(t.ev_wake_fd, &t, &eventsTryNext, 221)) stream_passed += 1;
  1530. } else if (w.burst(comp_wake_fd, null, &completionsTryNext, 221)) global_passed += 1;
  1531. }
  1532. }
  1533. try w.result("fetch stream chunk/done", stream_passed);
  1534. try w.result("fetch global chunk/done", global_passed);
  1535. try w.require(&.{stream_passed, global_passed});
  1536. }
  1537. // A full local accept queue drops subsequent SYNs without relying on routing.
  1538. // Every descriptor is owned by the fixture or the test, including failure paths.
  1539. const ConnectFixture = struct {
  1540. blackhole: i32,
  1541. queued: i32,
  1542. good: i32,
  1543. refused: i32,
  1544. addresses: [3]c.struct_sockaddr_in,
  1545. fn init() !ConnectFixture {
  1546. const blackhole = try listener(true);
  1547. errdefer _ = c.close(blackhole);
  1548. const queued = c.socket(c.AF_INET, c.SOCK_STREAM, c.IPPROTO_TCP);
  1549. if (queued < 0) return error.Socket;
  1550. errdefer _ = c.close(queued);
  1551. var black_addr = try boundAddress(blackhole);
  1552. if (c.connect(queued, @ptrCast(&black_addr), @sizeOf(c.struct_sockaddr_in)) != 0) return error.Connect;
  1553. const good = try listener(true);
  1554. errdefer _ = c.close(good);
  1555. // Bound but not listening reserves a reliably refused destination.
  1556. const refused = try listener(false);
  1557. errdefer _ = c.close(refused);
  1558. return .{ .blackhole = blackhole, .queued = queued, .good = good, .refused = refused, .addresses = .{ black_addr, try boundAddress(good), try boundAddress(refused) } };
  1559. }
  1560. fn address(port: u16) c.struct_sockaddr_in {
  1561. var addr = std.mem.zeroes(c.struct_sockaddr_in);
  1562. addr.sin_family = c.AF_INET;
  1563. addr.sin_port = std.mem.nativeToBig(u16, port);
  1564. addr.sin_addr.s_addr = std.mem.nativeToBig(u32, 0x7f000001);
  1565. return addr;
  1566. }
  1567. fn boundAddress(fd: i32) !c.struct_sockaddr_in {
  1568. var addr: c.struct_sockaddr_in = undefined;
  1569. var len: c.socklen_t = @sizeOf(c.struct_sockaddr_in);
  1570. if (c.getsockname(fd, @ptrCast(&addr), &len) != 0) return error.GetSockName;
  1571. return addr;
  1572. }
  1573. fn listener(listen: bool) !i32 {
  1574. const fd = c.socket(c.AF_INET, c.SOCK_STREAM, c.IPPROTO_TCP);
  1575. if (fd < 0) return error.Socket;
  1576. errdefer _ = c.close(fd);
  1577. const one: c_int = 1;
  1578. _ = c.setsockopt(fd, c.SOL_SOCKET, c.SO_REUSEADDR, &one, @sizeOf(c_int));
  1579. // The kernel assigns a separate port for each live fixture socket.
  1580. var addr = address(0);
  1581. if (c.bind(fd, @ptrCast(&addr), @sizeOf(c.struct_sockaddr_in)) != 0) return error.Bind;
  1582. if (listen and c.listen(fd, 0) != 0) return error.Listen;
  1583. return fd;
  1584. }
  1585. fn info(self: *ConnectFixture, index: usize, next: ?*c.struct_addrinfo) c.struct_addrinfo {
  1586. var ai = std.mem.zeroes(c.struct_addrinfo);
  1587. ai.ai_family = c.AF_INET;
  1588. ai.ai_socktype = c.SOCK_STREAM;
  1589. ai.ai_protocol = c.IPPROTO_TCP;
  1590. ai.ai_addr = @ptrCast(&self.addresses[index]);
  1591. ai.ai_addrlen = @sizeOf(c.struct_sockaddr_in);
  1592. ai.ai_next = next;
  1593. return ai;
  1594. }
  1595. fn deinit(self: ConnectFixture) void {
  1596. _ = c.close(self.queued);
  1597. _ = c.close(self.blackhole);
  1598. _ = c.close(self.good);
  1599. _ = c.close(self.refused);
  1600. }
  1601. };
  1602. test "connect falls back after a blackholed first address" {
  1603. var fixture = try ConnectFixture.init();
  1604. defer fixture.deinit();
  1605. var good = fixture.info(1, null);
  1606. var first = fixture.info(0, &good);
  1607. var err: []const u8 = "";
  1608. const start = nowMs();
  1609. const fd = tcpConnectAddresses(&first, start + 1200, &err);
  1610. defer if (fd) |f| {
  1611. _ = c.close(f);
  1612. };
  1613. const elapsed = nowMs() - start;
  1614. std.debug.print("blackhole + good: {d} ms, {s}\n", .{ elapsed, err });
  1615. try std.testing.expect(fd != null);
  1616. try std.testing.expect(elapsed >= 250 and elapsed < 550);
  1617. }
  1618. test "single blackholed address keeps the remaining whole-exchange budget" {
  1619. var fixture = try ConnectFixture.init();
  1620. defer fixture.deinit();
  1621. var first = fixture.info(0, null);
  1622. var err: []const u8 = "";
  1623. const start = nowMs();
  1624. // Model 200 ms already spent in DNS: only 650 ms of 850 ms remains.
  1625. const fd = tcpConnectAddresses(&first, start + 850 - 200, &err);
  1626. defer if (fd) |f| {
  1627. _ = c.close(f);
  1628. };
  1629. const elapsed = nowMs() - start;
  1630. std.debug.print("single blackhole: {d} ms, {s}\n", .{ elapsed, err });
  1631. try std.testing.expect(fd == null);
  1632. try std.testing.expectEqualStrings("timed out", err);
  1633. try std.testing.expect(elapsed >= 600 and elapsed < 900);
  1634. }
  1635. test "refused first address falls back immediately" {
  1636. var fixture = try ConnectFixture.init();
  1637. defer fixture.deinit();
  1638. var good = fixture.info(1, null);
  1639. var first = fixture.info(2, &good);
  1640. var err: []const u8 = "";
  1641. const start = nowMs();
  1642. const fd = tcpConnectAddresses(&first, start + 1200, &err);
  1643. defer if (fd) |f| {
  1644. _ = c.close(f);
  1645. };
  1646. const elapsed = nowMs() - start;
  1647. std.debug.print("refused + good: {d} ms, {s}\n", .{ elapsed, err });
  1648. try std.testing.expect(fd != null);
  1649. try std.testing.expect(elapsed < 250);
  1650. }
  1651. test "expired whole-exchange deadline does not connect" {
  1652. var fixture = try ConnectFixture.init();
  1653. defer fixture.deinit();
  1654. var good = fixture.info(1, null);
  1655. var err: []const u8 = "";
  1656. const fd = tcpConnectAddresses(&good, nowMs() - 1, &err);
  1657. defer if (fd) |f| {
  1658. _ = c.close(f);
  1659. };
  1660. try std.testing.expect(fd == null);
  1661. try std.testing.expectEqualStrings("timed out", err);
  1662. }
  1663. test "redirect origin includes scheme host and effective port" {
  1664. const base = parseUrl("https://example.com/start").?;
  1665. try std.testing.expect(sameOrigin(base, parseUrl("https://EXAMPLE.COM:443/next").?));
  1666. try std.testing.expect(!sameOrigin(base, parseUrl("http://example.com/next").?));
  1667. try std.testing.expect(!sameOrigin(base, parseUrl("https://example.com:444/next").?));
  1668. try std.testing.expect(!sameOrigin(base, parseUrl("https://other.example/next").?));
  1669. }
  1670. test "redirect credentials use case insensitive header names" {
  1671. for ([_][]const u8{ "Authorization", "PROXY-AUTHORIZATION", "cOoKiE" }) |name| {
  1672. try std.testing.expect(sensitiveHeader(name));
  1673. }
  1674. try std.testing.expect(!sensitiveHeader("X-Test"));
  1675. }
  1676. fn connectFdCount() !usize {
  1677. const dir = c.opendir("/proc/self/fd") orelse return error.OpenDir;
  1678. defer _ = c.closedir(dir);
  1679. var count: usize = 0;
  1680. while (true) {
  1681. const entry = c.readdir(dir);
  1682. if (entry == null) break;
  1683. if (entry[0].d_name[0] != '.') count += 1;
  1684. }
  1685. return count;
  1686. }
  1687. fn releaseConnectQueue(fd: i32) void {
  1688. _ = c.usleep(450_000);
  1689. const accepted = c.accept(fd, null, null);
  1690. if (accepted >= 0) _ = c.close(accepted);
  1691. }
  1692. test "slow first address survives a refused second address without leaking fds" {
  1693. const before = try connectFdCount();
  1694. {
  1695. var fixture = try ConnectFixture.init();
  1696. defer fixture.deinit();
  1697. const release = try std.Thread.spawn(.{}, releaseConnectQueue, .{fixture.blackhole});
  1698. defer release.join();
  1699. var refused = fixture.info(2, null);
  1700. var first = fixture.info(0, &refused);
  1701. var err: []const u8 = "";
  1702. const start = nowMs();
  1703. const fd = tcpConnectAddresses(&first, start + 2400, &err);
  1704. defer if (fd) |f| { _ = c.close(f); };
  1705. const elapsed = nowMs() - start;
  1706. std.debug.print("slow + refused: {d} ms, {s}\n", .{ elapsed, err });
  1707. try std.testing.expect(fd != null);
  1708. try std.testing.expect(elapsed > 300 and elapsed < 2400);
  1709. try std.testing.expect(linux.fcntl(fd.?, linux.F.GETFL, 0) & O_NONBLOCK == 0);
  1710. var peer: c.struct_sockaddr_in = undefined;
  1711. var len: c.socklen_t = @sizeOf(c.struct_sockaddr_in);
  1712. try std.testing.expect(c.getpeername(fd.?, @ptrCast(&peer), &len) == 0);
  1713. try std.testing.expectEqual(fixture.addresses[0].sin_port, peer.sin_port);
  1714. }
  1715. try std.testing.expectEqual(before, try connectFdCount());
  1716. }
  1717. test "all refused addresses preserve the error without leaking fds" {
  1718. const before = try connectFdCount();
  1719. {
  1720. var fixture = try ConnectFixture.init();
  1721. defer fixture.deinit();
  1722. var second = fixture.info(2, null);
  1723. var first = fixture.info(2, &second);
  1724. var err: []const u8 = "";
  1725. const start = nowMs();
  1726. const fd = tcpConnectAddresses(&first, start + 1200, &err);
  1727. defer if (fd) |f| { _ = c.close(f); };
  1728. try std.testing.expect(fd == null);
  1729. try std.testing.expectEqualStrings("connection refused", err);
  1730. try std.testing.expect(nowMs() - start < 250);
  1731. }
  1732. try std.testing.expectEqual(before, try connectFdCount());
  1733. }
  1734. test "all silent addresses wait until the deadline without leaking fds" {
  1735. const before = try connectFdCount();
  1736. {
  1737. var fixture = try ConnectFixture.init();
  1738. defer fixture.deinit();
  1739. var second = fixture.info(0, null);
  1740. var first = fixture.info(0, &second);
  1741. var err: []const u8 = "";
  1742. const start = nowMs();
  1743. const fd = tcpConnectAddresses(&first, start + 750, &err);
  1744. defer if (fd) |f| { _ = c.close(f); };
  1745. try std.testing.expect(fd == null);
  1746. try std.testing.expectEqualStrings("timed out", err);
  1747. const elapsed = nowMs() - start;
  1748. try std.testing.expect(elapsed >= 700 and elapsed < 1000);
  1749. }
  1750. try std.testing.expectEqual(before, try connectFdCount());
  1751. }
  1752. test "pending first address and refused last address still time out at deadline" {
  1753. const before = try connectFdCount();
  1754. {
  1755. var fixture = try ConnectFixture.init();
  1756. defer fixture.deinit();
  1757. var refused = fixture.info(2, null);
  1758. var first = fixture.info(0, &refused);
  1759. var err: []const u8 = "";
  1760. const start = nowMs();
  1761. const fd = tcpConnectAddresses(&first, start + 750, &err);
  1762. defer if (fd) |f| { _ = c.close(f); };
  1763. try std.testing.expect(fd == null);
  1764. try std.testing.expectEqualStrings("timed out", err);
  1765. try std.testing.expect(nowMs() - start >= 700);
  1766. }
  1767. try std.testing.expectEqual(before, try connectFdCount());
  1768. }
  1769. test "winner closes multiple pending losers without leaking fds" {
  1770. const before = try connectFdCount();
  1771. {
  1772. var fixture = try ConnectFixture.init();
  1773. defer fixture.deinit();
  1774. var good = fixture.info(1, null);
  1775. var second = fixture.info(0, &good);
  1776. var first = fixture.info(0, &second);
  1777. var err: []const u8 = "";
  1778. const start = nowMs();
  1779. const fd = tcpConnectAddresses(&first, start + 1500, &err);
  1780. defer if (fd) |f| { _ = c.close(f); };
  1781. try std.testing.expect(fd != null);
  1782. const elapsed = nowMs() - start;
  1783. try std.testing.expect(elapsed >= 550 and elapsed < 1000);
  1784. try std.testing.expect(linux.fcntl(fd.?, linux.F.GETFL, 0) & O_NONBLOCK == 0);
  1785. }
  1786. try std.testing.expectEqual(before, try connectFdCount());
  1787. }
  1788. test "invalid address preserves connection failed without leaking fds" {
  1789. const before = try connectFdCount();
  1790. {
  1791. var fixture = try ConnectFixture.init();
  1792. defer fixture.deinit();
  1793. var invalid = fixture.info(1, null);
  1794. invalid.ai_addrlen = 1;
  1795. var err: []const u8 = "";
  1796. const fd = tcpConnectAddresses(&invalid, nowMs() + 750, &err);
  1797. defer if (fd) |f| { _ = c.close(f); };
  1798. try std.testing.expect(fd == null);
  1799. try std.testing.expectEqualStrings("connection failed", err);
  1800. }
  1801. try std.testing.expectEqual(before, try connectFdCount());
  1802. }

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