gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit65d5f80a65d5f80alogmre65d5f80a/plugins/fetch/fetch.zig

61.2 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. // That split is what makes `concurrent [ fetchStart(a), fetchStart(b), … ]` put N
  11. // requests on the wire AT ONCE: a `concurrent` arm runs to completion before its
  12. // sibling starts (nothing in the interpreter yields today), so an arm that blocked
  13. // on the socket would serialize the whole group. An arm that only starts a thread
  14. // does not. `fetch()` in server.hl is `fetchStart(…).response()` — start plus wait,
  15. // the familiar one-liner, for code that has nothing else to do.
  16. //
  17. // THE EVENT LOOP is never blocked by a fetch in flight: no loop thread is inside a
  18. // socket call, and a completed request rings the mission-125 BELL — `fetch.completions`
  19. // is an ordinary loop source with a `wake_fd`, so an `on fetched(ev)` handler is woken
  20. // by the same `epoll_wait` that wakes an http1 request. (The wait in `result()` is a
  21. // wait like any other plugin call's: it blocks the FIBER that asked. Starting the
  22. // fetches early and reading them later is what keeps a server serving, and the
  23. // completions source is how a server never has to wait at all.)
  24. //
  25. // TLS is `plugins/http/tls_common.zig` — the same module hl:http1 and hl:http2 use,
  26. // extended with a client half in this mission. Verification is ON: system trust
  27. // store plus hostname checking, with `caFile` naming an EXTRA anchor for a test
  28. // fixture's self-signed certificate. There is no verify-off switch at all.
  29. //
  30. // HTTP/1.1 only. An h2 client is a later slice: it needs ALPN on the client side and
  31. // a multiplexed connection pool, neither of which this file has. `connection: close`
  32. // on every request, so there is no pool to keep coherent either.
  33. const std = @import("std");
  34. const api = @import("plugin_api");
  35. const http = @import("http_common");
  36. const tls = @import("tls_common");
  37. const HlValue = api.HlValue;
  38. const HlField = api.HlField;
  39. const HlObject = api.HlObject;
  40. const HlIterator = api.HlIterator;
  41. const HlHandle = api.HlHandle;
  42. const c = @cImport({
  43. @cInclude("netdb.h");
  44. @cInclude("sys/socket.h");
  45. @cInclude("sys/time.h");
  46. @cInclude("unistd.h");
  47. @cInclude("netinet/in.h");
  48. @cInclude("netinet/tcp.h");
  49. });
  50. // requests run on their own threads: the plugins' allocator (plugin_api.zig)
  51. const allocator = api.allocator;
  52. const linux = std.os.linux;
  53. const libc = std.c;
  54. // pthread rather than std.Thread.Mutex, exactly as hl:http1 does: this is a `.so`
  55. // loaded into a binary built by a possibly different Zig, and the C primitives are
  56. // the ones whose ABI is fixed by the platform rather than by the standard library.
  57. const PthreadMutex = libc.pthread_mutex_t;
  58. const PthreadCond = libc.pthread_cond_t;
  59. fn mutexLock(m: *PthreadMutex) void {
  60. _ = libc.pthread_mutex_lock(m);
  61. }
  62. fn mutexUnlock(m: *PthreadMutex) void {
  63. _ = libc.pthread_mutex_unlock(m);
  64. }
  65. fn condBroadcast(cnd: *PthreadCond) void {
  66. _ = libc.pthread_cond_broadcast(cnd);
  67. }
  68. fn condWait(cnd: *PthreadCond, m: *PthreadMutex) void {
  69. _ = libc.pthread_cond_wait(cnd, m);
  70. }
  71. fn logMsg(msg: []const u8) void {
  72. _ = linux.write(2, msg.ptr, msg.len);
  73. }
  74. fn logFmt(comptime fmt: []const u8, args: anytype) void {
  75. var buf: [512]u8 = undefined;
  76. const s = std.fmt.bufPrint(&buf, fmt, args) catch return;
  77. logMsg(s);
  78. }
  79. // ── Limits, all of them documented defaults rather than hard walls ───────────
  80. /// No answer at all within this many milliseconds is a failed fetch. Overridable
  81. /// per call with `timeoutMs`; it covers the WHOLE exchange (DNS, connect,
  82. /// handshake, request, response, and every redirect hop), not one syscall.
  83. const DEFAULT_TIMEOUT_MS: i64 = 30_000;
  84. /// How many 3xx hops are followed before the fetch fails with "too many redirects".
  85. /// Overridable with `maxRedirects`; 0 means the 3xx is RETURNED as the response.
  86. const DEFAULT_MAX_REDIRECTS: u32 = 5;
  87. /// A response body larger than this fails rather than growing the process without
  88. /// bound — a client that pulls other people's APIs must not be a memory bomb.
  89. const MAX_BODY: usize = 32 * 1024 * 1024;
  90. /// O_NONBLOCK on x86-64 Linux. Spelled here because <fcntl.h> cannot be imported
  91. /// (see tcpConnect); it is an ABI constant, not a libc detail.
  92. const O_NONBLOCK: usize = 0o4000;
  93. const Header = struct {
  94. name: []u8,
  95. value: []u8,
  96. };
  97. fn freeHeaders(list: []Header) void {
  98. for (list) |h| {
  99. allocator.free(h.name);
  100. allocator.free(h.value);
  101. }
  102. allocator.free(list);
  103. }
  104. // ── The request, as the ticket carries it ────────────────────────────────────
  105. const Request = struct {
  106. method: []u8,
  107. url: []u8,
  108. headers: []Header,
  109. body: []u8,
  110. has_body: bool,
  111. json_body: bool,
  112. timeout_ms: i64,
  113. max_redirects: u32,
  114. ca_file: ?[]u8,
  115. tag: []u8,
  116. /// STREAMING (the LLM-token mode): deliver the body INCREMENTALLY as chunk
  117. /// events on the completions source instead of accumulating it. The final
  118. /// completion then carries status/headers and an EMPTY body — the chunks
  119. /// were the body. Requires an armed completions source; `result()` still
  120. /// works and yields the empty-body summary when the stream ends.
  121. stream: bool = false,
  122. fn deinit(self: *Request) void {
  123. allocator.free(self.method);
  124. allocator.free(self.url);
  125. freeHeaders(self.headers);
  126. allocator.free(self.body);
  127. if (self.ca_file) |ca| allocator.free(ca);
  128. allocator.free(self.tag);
  129. }
  130. };
  131. // ── The ticket: one in-flight (or finished) request ──────────────────────────
  132. const Ticket = struct {
  133. mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER,
  134. cond: PthreadCond = libc.PTHREAD_COND_INITIALIZER,
  135. done: bool = false,
  136. thread: ?std.Thread = null,
  137. req: Request,
  138. status: u16 = 0,
  139. final_url: []u8 = &.{},
  140. headers: []Header = &.{},
  141. body: []u8 = &.{},
  142. /// Non-null = the fetch failed and this is the located message the handle
  143. /// hands back as an `hl_error`.
  144. err: ?[]u8 = null,
  145. /// ABORT (the LLM-interrupt primitive): the socket currently carrying this
  146. /// request, visible under the ticket mutex so `fetchAbort(tag)` can
  147. /// shutdown() it from the interpreter thread — the read unblocks, the peer
  148. /// sees the disconnect and stops generating. -1 = none in flight.
  149. live_fd: i32 = -1,
  150. aborted: bool = false,
  151. /// INSTANCE EVENTS (stream mode): a streaming ticket carries its OWN frame
  152. /// queue and bell, created at start — before the worker exists — so no chunk
  153. /// can outrun the arming. `handle.events()` wraps them into a loop source;
  154. /// pending_fetch.hl registers it and re-emits `chunk`/`done` at itself.
  155. /// -1 = not a streaming ticket (completions go the global route, if armed).
  156. ev_queue: std.ArrayListUnmanaged(Completion) = .empty,
  157. ev_wake_fd: i32 = -1,
  158. /// THE PARKED FIBER'S BELL (lazy, under the mutex): `doneFd()` makes an eventfd
  159. /// that finish() rings, so a `concurrent` group whose arms all wait on fetches
  160. /// sleeps in poll() on these instead of spinning. -1 = nobody asked.
  161. done_fd: i32 = -1,
  162. fn doneFd(self: *Ticket) i32 {
  163. mutexLock(&self.mutex);
  164. defer mutexUnlock(&self.mutex);
  165. if (self.done_fd < 0) {
  166. self.done_fd = http.makeWakeFd();
  167. if (self.done and self.done_fd >= 0) http.ringWake(self.done_fd);
  168. }
  169. return self.done_fd;
  170. }
  171. fn wait(self: *Ticket) void {
  172. mutexLock(&self.mutex);
  173. while (!self.done) condWait(&self.cond, &self.mutex);
  174. mutexUnlock(&self.mutex);
  175. }
  176. fn isDone(self: *Ticket) bool {
  177. mutexLock(&self.mutex);
  178. defer mutexUnlock(&self.mutex);
  179. return self.done;
  180. }
  181. fn setLiveFd(self: *Ticket, fd: i32) bool {
  182. mutexLock(&self.mutex);
  183. defer mutexUnlock(&self.mutex);
  184. if (self.aborted) return false; // aborted before the connect landed
  185. self.live_fd = fd;
  186. return true;
  187. }
  188. fn clearLiveFd(self: *Ticket) void {
  189. mutexLock(&self.mutex);
  190. self.live_fd = -1;
  191. mutexUnlock(&self.mutex);
  192. }
  193. /// The abort itself: mark, and shutdown() any in-flight socket so the
  194. /// worker's blocking read returns NOW. Closing is still the worker's job
  195. /// (its defer owns the fd); shutdown only cuts the conversation.
  196. fn abort(self: *Ticket) void {
  197. mutexLock(&self.mutex);
  198. self.aborted = true;
  199. if (self.live_fd >= 0) _ = c.shutdown(self.live_fd, 2); // SHUT_RDWR
  200. mutexUnlock(&self.mutex);
  201. }
  202. fn finish(self: *Ticket) void {
  203. mutexLock(&self.mutex);
  204. self.done = true;
  205. http.ringWake(self.done_fd);
  206. condBroadcast(&self.cond);
  207. mutexUnlock(&self.mutex);
  208. }
  209. fn fail(self: *Ticket, comptime fmt: []const u8, args: anytype) void {
  210. self.err = std.fmt.allocPrint(allocator, fmt, args) catch null;
  211. }
  212. };
  213. // ── URL ──────────────────────────────────────────────────────────────────────
  214. const Url = struct {
  215. https: bool,
  216. host: []const u8,
  217. port: u16,
  218. /// path + query, always starting with '/'
  219. target: []const u8,
  220. };
  221. /// `scheme://host[:port][/path][?query]`. Only http and https; a URL with
  222. /// credentials or an IPv6 literal is refused rather than half-understood.
  223. fn parseUrl(url: []const u8) ?Url {
  224. var rest: []const u8 = undefined;
  225. var https = false;
  226. if (std.mem.startsWith(u8, url, "http://")) {
  227. rest = url["http://".len..];
  228. } else if (std.mem.startsWith(u8, url, "https://")) {
  229. rest = url["https://".len..];
  230. https = true;
  231. } else return null;
  232. const slash = std.mem.indexOfScalar(u8, rest, '/');
  233. const authority = if (slash) |s| rest[0..s] else rest;
  234. const target = if (slash) |s| rest[s..] else "/";
  235. if (authority.len == 0) return null;
  236. if (std.mem.indexOfScalar(u8, authority, '@') != null) return null;
  237. if (std.mem.indexOfScalar(u8, authority, '[') != null) return null;
  238. var host = authority;
  239. var port: u16 = if (https) 443 else 80;
  240. if (std.mem.lastIndexOfScalar(u8, authority, ':')) |colon| {
  241. host = authority[0..colon];
  242. port = std.fmt.parseInt(u16, authority[colon + 1 ..], 10) catch return null;
  243. }
  244. if (host.len == 0) return null;
  245. return .{ .https = https, .host = host, .port = port, .target = target };
  246. }
  247. /// Resolve a `Location` against the URL it came from: absolute stays, `/x` replaces
  248. /// the path, anything else is relative to the current directory of the path.
  249. fn resolveLocation(base: []const u8, loc: []const u8) ?[]u8 {
  250. if (loc.len == 0) return null;
  251. if (std.mem.startsWith(u8, loc, "http://") or std.mem.startsWith(u8, loc, "https://")) {
  252. return allocator.dupe(u8, loc) catch null;
  253. }
  254. const b = parseUrl(base) orelse return null;
  255. const scheme = if (b.https) "https" else "http";
  256. const default_port: u16 = if (b.https) 443 else 80;
  257. var authority_buf: [300]u8 = undefined;
  258. const authority = if (b.port == default_port)
  259. std.fmt.bufPrint(&authority_buf, "{s}", .{b.host}) catch return null
  260. else
  261. std.fmt.bufPrint(&authority_buf, "{s}:{d}", .{ b.host, b.port }) catch return null;
  262. if (loc[0] == '/') {
  263. return std.fmt.allocPrint(allocator, "{s}://{s}{s}", .{ scheme, authority, loc }) catch null;
  264. }
  265. // Relative: cut the base target back to its last '/'.
  266. const path_only = if (std.mem.indexOfScalar(u8, b.target, '?')) |q| b.target[0..q] else b.target;
  267. const cut = std.mem.lastIndexOfScalar(u8, path_only, '/') orelse 0;
  268. return std.fmt.allocPrint(allocator, "{s}://{s}{s}/{s}", .{ scheme, authority, path_only[0..cut], loc }) catch null;
  269. }
  270. // ── Socket plumbing ──────────────────────────────────────────────────────────
  271. fn nowMs() i64 {
  272. var ts: linux.timespec = undefined;
  273. _ = linux.clock_gettime(linux.CLOCK.MONOTONIC, &ts);
  274. return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
  275. }
  276. /// Connect to host:port, giving up after `budget_ms`. The connect is non-blocking
  277. /// plus a poll so the DEADLINE is honoured even when the peer never answers SYN;
  278. /// the socket is put back into blocking mode with SO_RCVTIMEO/SO_SNDTIMEO after,
  279. /// which is what bounds the read side.
  280. fn tcpConnect(host: []const u8, port: u16, budget_ms: i64, err_out: *[]const u8) ?i32 {
  281. if (budget_ms <= 0) {
  282. err_out.* = "timed out";
  283. return null;
  284. }
  285. var host_buf: [256]u8 = undefined;
  286. if (host.len >= host_buf.len) {
  287. err_out.* = "host name too long";
  288. return null;
  289. }
  290. @memcpy(host_buf[0..host.len], host);
  291. host_buf[host.len] = 0;
  292. var port_buf: [8]u8 = undefined;
  293. const port_str = std.fmt.bufPrintZ(&port_buf, "{d}", .{port}) catch {
  294. err_out.* = "bad port";
  295. return null;
  296. };
  297. var hints: c.struct_addrinfo = std.mem.zeroes(c.struct_addrinfo);
  298. hints.ai_family = c.AF_UNSPEC;
  299. hints.ai_socktype = c.SOCK_STREAM;
  300. hints.ai_protocol = c.IPPROTO_TCP;
  301. var res: ?*c.struct_addrinfo = null;
  302. if (c.getaddrinfo(@ptrCast(&host_buf), port_str.ptr, &hints, &res) != 0 or res == null) {
  303. err_out.* = "could not resolve host";
  304. return null;
  305. }
  306. defer c.freeaddrinfo(res);
  307. const deadline = nowMs() + budget_ms;
  308. var last: []const u8 = "connection failed";
  309. var it: ?*c.struct_addrinfo = res;
  310. while (it) |ai| : (it = ai.ai_next) {
  311. const remaining = deadline - nowMs();
  312. if (remaining <= 0) {
  313. err_out.* = "timed out";
  314. return null;
  315. }
  316. const fd_c = c.socket(ai.ai_family, ai.ai_socktype, ai.ai_protocol);
  317. if (fd_c < 0) {
  318. last = "could not create a socket";
  319. continue;
  320. }
  321. const fd: i32 = @intCast(fd_c);
  322. // fcntl straight from the kernel: glibc's <fcntl.h> does not survive
  323. // translate-c under _FORTIFY_SOURCE (its open() overloads are declared
  324. // with attribute error), and the flags are ABI constants either way.
  325. const flags = linux.fcntl(fd, linux.F.GETFL, 0);
  326. _ = linux.fcntl(fd, linux.F.SETFL, flags | @as(usize, O_NONBLOCK));
  327. var connected = false;
  328. if (c.connect(fd, ai.ai_addr, ai.ai_addrlen) == 0) {
  329. connected = true;
  330. } else {
  331. // linux.poll, not glibc's: <poll.h> is fortified too (see above).
  332. var pfd = [_]linux.pollfd{.{ .fd = fd, .events = linux.POLL.OUT, .revents = 0 }};
  333. const pr: isize = @bitCast(linux.poll(&pfd, 1, @intCast(@min(remaining, std.math.maxInt(i32)))));
  334. if (pr > 0) {
  335. var so_err: c_int = 0;
  336. var len: c.socklen_t = @sizeOf(c_int);
  337. _ = c.getsockopt(fd, c.SOL_SOCKET, c.SO_ERROR, &so_err, &len);
  338. if (so_err == 0) {
  339. connected = true;
  340. } else if (so_err == 111) {
  341. last = "connection refused";
  342. } else {
  343. last = "connection failed";
  344. }
  345. } else if (pr == 0) {
  346. _ = c.close(fd);
  347. err_out.* = "timed out";
  348. return null;
  349. } else {
  350. last = "connection failed";
  351. }
  352. }
  353. if (!connected) {
  354. _ = c.close(fd);
  355. continue;
  356. }
  357. _ = linux.fcntl(fd, linux.F.SETFL, flags);
  358. const left = @max(deadline - nowMs(), 1);
  359. var tv = c.struct_timeval{
  360. .tv_sec = @intCast(@divTrunc(left, 1000)),
  361. .tv_usec = @intCast(@rem(left, 1000) * 1000),
  362. };
  363. _ = c.setsockopt(fd, c.SOL_SOCKET, c.SO_RCVTIMEO, &tv, @sizeOf(c.struct_timeval));
  364. _ = c.setsockopt(fd, c.SOL_SOCKET, c.SO_SNDTIMEO, &tv, @sizeOf(c.struct_timeval));
  365. const one: c_int = 1;
  366. _ = c.setsockopt(fd, c.IPPROTO_TCP, c.TCP_NODELAY, &one, @sizeOf(c_int));
  367. return fd;
  368. }
  369. err_out.* = last;
  370. return null;
  371. }
  372. /// The one place either transport is read or written, so the HTTP exchange below
  373. /// is written once for http:// and https://.
  374. const Conn = struct {
  375. fd: i32,
  376. ssl: ?*tls.SSL = null,
  377. tls_ctx: ?*const tls.TlsContext = null,
  378. fn writeAll(self: *Conn, data: []const u8) bool {
  379. if (self.ssl) |ssl| {
  380. return self.tls_ctx.?.writeAll(ssl, data) == data.len;
  381. }
  382. var sent: usize = 0;
  383. while (sent < data.len) {
  384. const n = c.write(self.fd, data.ptr + sent, data.len - sent);
  385. if (n <= 0) return false;
  386. sent += @intCast(n);
  387. }
  388. return true;
  389. }
  390. /// >0 bytes, 0 = clean end of body, <0 = error (or a socket timeout, which the
  391. /// caller separates from an error by looking at the clock).
  392. fn read(self: *Conn, buf: []u8) isize {
  393. if (self.ssl) |ssl| {
  394. const n = self.tls_ctx.?.read(ssl, buf);
  395. if (n > 0) return n;
  396. const e = self.tls_ctx.?.getError(ssl, n);
  397. if (e == tls.SSL_ERROR_ZERO_RETURN) return 0;
  398. return -1;
  399. }
  400. return c.read(self.fd, buf.ptr, buf.len);
  401. }
  402. fn close(self: *Conn) void {
  403. if (self.ssl) |ssl| {
  404. self.tls_ctx.?.shutdownAndFree(ssl);
  405. self.ssl = null;
  406. }
  407. _ = c.close(self.fd);
  408. }
  409. };
  410. // ── The client TLS context, one per CA file ──────────────────────────────────
  411. //
  412. // An SSL_CTX is expensive (it reads the system trust store) and thread-safe, so it
  413. // is built once per distinct `caFile` and shared. The map is tiny by construction:
  414. // a program has a system-trust context and at most a handful of pinned fixtures.
  415. const CtxEntry = struct {
  416. key: []u8,
  417. ctx: tls.TlsContext,
  418. };
  419. var ctx_mutex: PthreadMutex = libc.PTHREAD_MUTEX_INITIALIZER;
  420. var ctx_list: std.ArrayListUnmanaged(CtxEntry) = .empty;
  421. fn clientCtx(ca_file: ?[]const u8, err_out: *[]const u8) ?*const tls.TlsContext {
  422. const key = ca_file orelse "";
  423. mutexLock(&ctx_mutex);
  424. defer mutexUnlock(&ctx_mutex);
  425. for (ctx_list.items) |*e| {
  426. if (std.mem.eql(u8, e.key, key)) return &e.ctx;
  427. }
  428. const ctx = tls.TlsContext.initClient(.{ .ca_file = ca_file, .tag = "fetch" }) orelse {
  429. err_out.* = "https is not available (no usable OpenSSL, or the caFile could not be loaded)";
  430. return null;
  431. };
  432. const key_copy = allocator.dupe(u8, key) catch {
  433. err_out.* = "out of memory";
  434. return null;
  435. };
  436. ctx_list.append(allocator, .{ .key = key_copy, .ctx = ctx }) catch {
  437. allocator.free(key_copy);
  438. err_out.* = "out of memory";
  439. return null;
  440. };
  441. return &ctx_list.items[ctx_list.items.len - 1].ctx;
  442. }
  443. // ── One HTTP exchange ────────────────────────────────────────────────────────
  444. const Exchange = struct {
  445. status: u16 = 0,
  446. headers: []Header = &.{},
  447. body: []u8 = &.{},
  448. fn deinit(self: *Exchange) void {
  449. freeHeaders(self.headers);
  450. allocator.free(self.body);
  451. }
  452. };
  453. fn headerValue(headers: []const Header, name: []const u8) ?[]const u8 {
  454. for (headers) |h| {
  455. if (std.ascii.eqlIgnoreCase(h.name, name)) return h.value;
  456. }
  457. return null;
  458. }
  459. fn hasHeader(headers: []const Header, name: []const u8) bool {
  460. return headerValue(headers, name) != null;
  461. }
  462. /// Send one request over one connection and read the whole response.
  463. /// `err_out` gets a short static reason; the caller adds the URL.
  464. /// The status code off a raw head, or null while unparseable.
  465. fn parseStatus(head: []const u8) ?u16 {
  466. var lines = std.mem.splitSequence(u8, head, "\r\n");
  467. const status_line = lines.next() orelse return null;
  468. var parts = std.mem.splitScalar(u8, status_line, ' ');
  469. _ = parts.next(); // HTTP/1.1
  470. const code = parts.next() orelse return null;
  471. return std.fmt.parseInt(u16, code, 10) catch null;
  472. }
  473. /// Head only → an Exchange with an EMPTY body (the chunks were the body).
  474. fn parseHeadOnly(head_raw: []const u8, err_out: *[]const u8) ?Exchange {
  475. // reuse the full parser on a synthetic complete response: the head as-is
  476. // (its transfer-encoding stripped so no body is expected) + no body.
  477. var synth: std.ArrayListUnmanaged(u8) = .empty;
  478. defer synth.deinit(allocator);
  479. var lines = std.mem.splitSequence(u8, head_raw[0 .. head_raw.len - 4], "\r\n");
  480. while (lines.next()) |line| {
  481. if (line.len > 18 and std.ascii.eqlIgnoreCase(line[0..18], "transfer-encoding:")) continue;
  482. if (line.len > 15 and std.ascii.eqlIgnoreCase(line[0..15], "content-length:")) continue;
  483. if (!add(&synth, line)) return oom(err_out);
  484. if (!add(&synth, "\r\n")) return oom(err_out);
  485. }
  486. if (!add(&synth, "\r\n")) return oom(err_out);
  487. return parseResponse(synth.items, err_out);
  488. }
  489. /// STREAM the body: post every decoded piece as a chunk frame until the peer
  490. /// closes (`connection: close` is on every request, so close IS the end).
  491. /// Chunked transfer is decoded incrementally; anything else streams as-is.
  492. fn streamBody(t: *Ticket, conn: *Conn, raw: *std.ArrayListUnmanaged(u8), he: usize, deadline: i64, err_out: *[]const u8) ?Exchange {
  493. defer raw.deinit(allocator);
  494. const chunked = blk: {
  495. if (findHeaderIn(raw.items[0..he], "transfer-encoding")) |v| {
  496. break :blk std.ascii.indexOfIgnoreCase(v, "chunked") != null;
  497. }
  498. break :blk false;
  499. };
  500. // chunked-decoder state, carried across reads
  501. var pending: std.ArrayListUnmanaged(u8) = .empty;
  502. defer pending.deinit(allocator);
  503. var remaining: usize = 0; // bytes left of the current chunk's data
  504. var done = false;
  505. // seed with whatever body bytes arrived along with the head
  506. if (raw.items.len > he) {
  507. pending.appendSlice(allocator, raw.items[he..]) catch return oom(err_out);
  508. }
  509. var buf: [16 * 1024]u8 = undefined;
  510. while (true) {
  511. // decode + post what we hold
  512. if (!chunked) {
  513. if (pending.items.len > 0) {
  514. postChunk(t, pending.items);
  515. pending.clearRetainingCapacity();
  516. }
  517. } else while (!done) {
  518. if (remaining > 0) {
  519. const take = @min(remaining, pending.items.len);
  520. if (take == 0) break;
  521. postChunk(t, pending.items[0..take]);
  522. std.mem.copyForwards(u8, pending.items, pending.items[take..]);
  523. pending.shrinkRetainingCapacity(pending.items.len - take);
  524. remaining -= take;
  525. if (remaining == 0) {
  526. // the CRLF after the chunk data
  527. if (pending.items.len < 2) break;
  528. std.mem.copyForwards(u8, pending.items, pending.items[2..]);
  529. pending.shrinkRetainingCapacity(pending.items.len - 2);
  530. }
  531. continue;
  532. }
  533. const nl = std.mem.indexOf(u8, pending.items, "\r\n") orelse break;
  534. const size_line = pending.items[0..nl];
  535. const semi = std.mem.indexOfScalar(u8, size_line, ';') orelse size_line.len;
  536. const n = std.fmt.parseInt(usize, std.mem.trim(u8, size_line[0..semi], " \t"), 16) catch {
  537. err_out.* = "the peer sent a malformed chunked body";
  538. return null;
  539. };
  540. std.mem.copyForwards(u8, pending.items, pending.items[nl + 2 ..]);
  541. pending.shrinkRetainingCapacity(pending.items.len - nl - 2);
  542. if (n == 0) {
  543. done = true;
  544. break;
  545. }
  546. remaining = n;
  547. }
  548. if (done) break;
  549. const n = conn.read(&buf);
  550. if (n == 0) break; // close IS the end (identity), or a truncated chunked stream
  551. if (n < 0) {
  552. if (nowMs() >= deadline) {
  553. err_out.* = "timed out";
  554. return null;
  555. }
  556. break;
  557. }
  558. pending.appendSlice(allocator, buf[0..@intCast(n)]) catch return oom(err_out);
  559. }
  560. return parseHeadOnly(raw.items[0..he], err_out);
  561. }
  562. fn exchange(t: *Ticket, url: Url, method: []const u8, body: []const u8, send_body: bool, deadline: i64, err_out: *[]const u8) ?Exchange {
  563. const budget = deadline - nowMs();
  564. const fd = tcpConnect(url.host, url.port, budget, 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. }

Branches

Latest commits

  • 65d5f80alogmre
  • dab74b0dW49 report, logmre
  • fd4fc028Exercise member status reads with a populated check statemre
  • 536ca6f9Allow repository members to read pull workflow APIs with user tokensmre
  • 705dd834W49 missionmre
  • b554cd5flogmre
  • f4c9440ddeploy.sh: tar --hard-dereference for the live data backupmre
  • 1a687b15Merge branch 'w48-member-merge'mre
  • 166c775fW48 report, logmre
  • 1b4623f0Members merge pull requests: API route, button on /pulls and /pulls/N, one shared merge pathmre
  • 1075c38cW48 mission, logmre
  • 17bdd0d6V37/V39 missions, logmre
  • 146de5f8Re-vendor gitoria to Hybriel set-day39 (51e921d7)mre
  • e874e44dtests/status-keyed: app token lives 60 s so it outlives the gate's two restartsmre
  • 270b8d61deploy.sh: DEPLOY_STOP_START=1 stops, waits for the old pid, then starts (mpackdb freeze, replaces the standby swap)mre
  • 3f9235b8project.hl: drop the dummy /pulls/:n component route (hybriel#294 is fixed in day37)mre
  • c90daf19Re-vendor gitoria to Hybriel set-day37 (f6b3d45b)mre
  • 03b5bb08W39 report to reports/, drop scratch repro, mission + logmre
  • 154d333fMerge w39-create-api: POST /api/repos with a user token (#39)mre
  • 149dd512Rewrite W39 reportmre