gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchreconnect-retryac6f4c6fL2: plain declaration for a in pickedNextmrereconnect-retry/plugins/fetch/fetch.zig

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

Branches

Latest commits

  • 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
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre
  • 89cdabb1Vendor Hybriel day41 (57054d9e): plugin dirs, set .somre
  • 1fecd6a7Merge branch 'records-day39' into mainJukebox
  • d6b3e068|||PR Records: day39 live (PR #2), mission 011 PR step, statusmre
  • 5fa19e89Merge branch 'day39' into mainJukebox
  • cfe95440|||PR day39 re-vendor: Hybriel 51e921d7 (bin 6b481aa7), ids kebab-case since hybriel#256: quoted state rule and tests use jb-shuffle / jb-repeatmre
  • f3614c9bRe-vendor to Hybriel day39 (51e921d7, bin 6b481aa7)mre
  • 9f5c6532Merge branch 'status-22-pr' into mainJukebox
  • 5838d6c7|||PR STATUS: #22 pending decision, PR-only rulemre
  • 29d2029cRecords: PR-only rule (Kunibert)mre
  • adacb0abRecords: neutral ticket rule, #22 decision recordedmre
  • b2d6f121Records: #308 hold liftedmre
  • 7ab67533Records: day39 on hold (hybriel#308)mre
  • 22f21739Records: note rebase before mergemre