gitoria

jukebox

All repositories: gitoria

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

18.8 KB

  1. # hl:http1 Plugin
  2. HTTP/1.1 server plugin for Hybriel. Epoll-based acceptor with I/O thread pool, optional TLS, keep-alive support.
  3. ## Two Usage Patterns
  4. ### 1. Event-based (class with `on request`)
  5. Extend `NativeHttpServer`, override `on request`, call `listen()`.
  6. ```hybriel
  7. import { NativeHttpServer, Response } from 'hl:http1';
  8. MyServer < NativeHttpServer {
  9. Number port = 8091;
  10. on request(req) {
  11. return new Response('<!DOCTYPE>
  12. <html>
  13. <head>
  14. <title>Hello World!</title>
  15. </head>
  16. <body>
  17. <h1>Hello World!</h1>
  18. <p>This could be your front page!</p>
  19. </body>
  20. </html>
  21. ', {
  22. status = 200;
  23. headers = {
  24. "Set-Cookie" = 'session=test';
  25. };
  26. });
  27. }
  28. }
  29. myServer = { port = 8091; } > new MyServer();
  30. ```
  31. The server runs in the event loop. Each incoming request is dispatched to `on request` as a fiber, so the process stays alive and can handle concurrent requests.
  32. ### 2. Iterator-based (`for (req of server)`)
  33. Call `listen(port)` directly, iterate requests in a loop.
  34. ```hybriel
  35. import { listen, Response } from 'hl:http1';
  36. server = listen(9123);
  37. for (req of server) {
  38. if (req.path == "/hello") {
  39. emit req.response(new Response('<!DOCTYPE>
  40. <html>
  41. <head>
  42. <title>Hello World!</title>
  43. </head>
  44. <body>
  45. <h1>Hello World!</h1>
  46. <p>This could be your front page!</p>
  47. </body>
  48. </html>
  49. ', {
  50. status = 200;
  51. headers = {
  52. "Set-Cookie" = 'session=test';
  53. };
  54. }));
  55. } else {
  56. emit req.response(new Response('Not found', { status = 404; }));
  57. }
  58. }
  59. ```
  60. This blocks on each iteration waiting for the next request. Simpler but sequential.
  61. ## Request Object
  62. Each request has these fields:
  63. | Field | Type | Description |
  64. |-------|------|-------------|
  65. | `method` | String | `"GET"`, `"POST"`, etc. |
  66. | `path` | String | `"/hello"`, `"/api/users"` |
  67. | `query` | Object | Parsed query params (keys/values) |
  68. | `headers` | Object | HTTP headers (keys/values) |
  69. | `body` | String or null | Request body — a `Content-Length` one, or a `Transfer-Encoding: chunked` one de-chunked |
  70. | `bytes` | Bytes | The same body as a Bytes, byte for byte (empty when there is none) |
  71. | `respond` | Handle | Response handle |
  72. ## Response Object
  73. Create a `Response` with body and optional options:
  74. ```hybriel
  75. // Basic
  76. new Response("Hello!")
  77. // With status and headers
  78. new Response('{"ok":true}', {
  79. status = 200;
  80. headers = {
  81. "Content-Type" = 'application/json';
  82. "Set-Cookie" = 'session=abc';
  83. };
  84. })
  85. // Error response
  86. new Response('Not found', { status = 404; })
  87. ```
  88. | Field | Type | Default | Description |
  89. |-------|------|---------|-------------|
  90. | `body` | String or Bytes | `''` | Response body; a Bytes is sent raw, as `application/octet-stream` unless `headers` name a type |
  91. | `status` | Number | `200` | HTTP status code |
  92. | `headers` | Object | `{}` | HTTP headers (key-value pairs) |
  93. ### Several values for one header (hybriel#222)
  94. A header value may be a list of strings. The server then writes one header line per entry, in the order given:
  95. ```hl
  96. return new Response('ok', { headers = {
  97. 'Set-Cookie' = ['sid=new; Path=/', 'sid=; Max-Age=0']
  98. } })
  99. ```
  100. Header names are compared without regard to case when the answer is built. Two keys that differ only in case, such as `'Set-Cookie'` and `'set-cookie'`, are merged into one list in the order they were written, so using both can never produce a duplicate. Values are never joined into one comma-separated line, which would be wrong for `Set-Cookie`. An empty list writes nothing, and entries that are not strings are skipped.
  101. ## NativeHttpServer Properties
  102. | Property | Type | Default | Description |
  103. |----------|------|---------|-------------|
  104. | `port` | Number | 8080 | Listen port |
  105. | `host` | String | "0.0.0.0" | Bind address |
  106. | `tls_cert` | String | null | Path to TLS certificate |
  107. | `tls_key` | String | null | Path to TLS private key |
  108. | `threads` | Number | 4 | I/O worker threads |
  109. ## Architecture
  110. ```
  111. Client → epoll acceptor thread → PARK (epoll) → I/O thread pool (TLS + parse)
  112. → request queue → event loop → on request fiber
  113. ```
  114. - Acceptor thread uses epoll to accept connections without blocking
  115. - I/O workers handle TLS handshake and HTTP parsing in parallel
  116. - Parsed requests go into an MPSC queue
  117. - The runtime event loop polls the queue (non-blocking) and spawns a fiber per request
  118. ### Parking: an idle connection costs no thread (mission 084)
  119. A worker's `read()` is blocking, so a connection handed to the pool occupies a whole
  120. worker until bytes arrive. Keep-alive connections used to be re-enqueued straight into the
  121. pool after each response, so an idle one still held a thread — with the default
  122. `threads = 4`, **four quiet sockets starved the server** and every later request hung
  123. (mission 075 saw this as "the second browser session's page never fires `load`").
  124. Connections are therefore **parked** in a dedicated epoll instance (`ParkedConns`) and only
  125. enter the worker queue once they are actually readable — or have hung up, which a worker
  126. reads as EOF and closes. Both the acceptor and the post-response keep-alive path park.
  127. An idle connection now costs one fd and zero threads.
  128. - A parked connection that stays silent for `PARK_IDLE_TIMEOUT_MS` (60s) is closed.
  129. - Workers set `SO_RCVTIMEO` (30s) on every connection as a backstop against a client that
  130. trickles headers; it is no longer the idle-timeout mechanism.
  131. - **An established TLS connection is never parked**: OpenSSL may hold already-decrypted
  132. plaintext that epoll on the raw fd cannot see. Those go straight to a worker, as before,
  133. so a TLS server is still starvable by idle keep-alive connections — the plain-HTTP path
  134. (and the pre-handshake TLS socket, whose ClientHello does arrive on the raw fd) is fixed.
  135. - Regression test: `tests/browser/tests/13-keepalive-starvation.mjs`.
  136. ### Independent WebSocket servers (ticket #354)
  137. Each `NativeWebSocketServer` owns its engine, event queue and connected peers.
  138. Several instances may listen in one process: `connect`, `message`, `pong` and
  139. `close` reach the instance that accepted the connection, and `broadcast(text)`
  140. sends only to that instance's peers. Closing one server leaves the others running.
  141. `NativeHttpServer.sockets()` also enables WebSockets only on that listener,
  142. including the socket used by hl:web.
  143. Regression: `HL_TEST_PORT=30090 node plugins/http1/tests/two-ws-servers.mjs`.
  144. ### WebSocket liveness sweep (mission 091)
  145. The WS reader loop (one thread, epoll, level-triggered EPOLLIN) already wakes on a 500ms
  146. timeout, so liveness costs no timer and no extra thread: on every tick it walks the
  147. upgraded sockets, pings the ones that have gone quiet, and drops the ones whose pong is
  148. overdue.
  149. A drop enqueues the **same `close` event a real FIN would have produced**, so every
  150. consumer above this plugin — hl:web's push subscription registry included — prunes through
  151. the path it already had. No new concept travels upward, and nothing at the `.hl` level
  152. needs a timer facility.
  153. Why it is needed: a peer that vanishes without closing (dead wifi, a suspended laptop, a
  154. host that never sent the FIN) leaves a socket that stays open and **writable**. A server
  155. with nothing to push at it never discovers the corpse, so before this the subscription was
  156. immortal. A closed tab is not this case — the browser's stack sends the FIN, and even under
  157. CDP offline emulation it still answers protocol pings (measured, mission 091), which is why
  158. the regression test's dead peer is a raw socket that goes silent rather than a tab.
  159. | Env var | Default | Meaning |
  160. |---------|---------|---------|
  161. | `HL_WS_PING_MS` | `15000` | a socket quiet this long is pinged |
  162. | `HL_WS_PONG_TIMEOUT_MS` | `10000` | a ping unanswered this long ⇒ the peer is gone |
  163. Read once when the engine starts; timeouts are measured on `CLOCK_MONOTONIC`, so an NTP
  164. step cannot make one fire early or never. Any inbound frame — of any opcode — counts as
  165. proof of life and clears an outstanding ping.
  166. - Regression test: `tests/browser/tests/23-ws-liveness-sweep.mjs` (includes the
  167. falsification: the same silent peer against a sweep-disabled server stays registered).
  168. ### The handshake's cookies + a cookie-grade random (mission 093)
  169. A WebSocket upgrade is an ordinary HTTP request, so the browser attaches the site's cookies
  170. to it. That is the one moment an upgraded socket can be attributed to whoever loaded the
  171. page — after the 101 the request and its headers are freed and the connection carries no
  172. identity of its own. The `connect` event therefore gained a sixth field:
  173. ```
  174. { kind, id, data, binary, code, cookie }
  175. ```
  176. `cookie` is the handshake's `Cookie:` header verbatim, non-empty on `connect` only. Nothing
  177. is parsed here: hl:web's session layer (`plugins/web/web_session.hl`) owns the cookie's name
  178. and meaning, and this plugin owns only its delivery.
  179. ```
  180. randomToken(Number n) // n lowercase hex chars, kernel CSPRNG (getrandom(2)), max 128
  181. ```
  182. A session id is the only thing between a stranger and someone else's session, so it may not
  183. come from a seeded PRNG — `hl:math`'s `random()` is a clock-seeded xoshiro whose state a
  184. handful of outputs reveals, which would make every other id derivable from one's own. This
  185. lives here because a session cookie is an HTTP artifact and this is the plugin that parses
  186. and writes one; it is currently the only CSPRNG reachable from `.hl`.
  187. - Regression test: `tests/browser/tests/25-sessions.mjs` (two real browser instances = two
  188. cookie jars = two sessions).
  189. Ticket #74 added `host` (the handshake's `Host:` header) and ticket #105 `headers`: every
  190. header of the handshake as `name: value` lines, names lowercase, non-empty on `connect` only.
  191. `NativeWebSocketServer` hands them to the `WsClient` as `client.headers`, a hash by name —
  192. which is where hl:web reads the headers a navigation over that socket is constructed with.
  193. ### TLS flag and peer address (hybriel#214)
  194. A server that terminates TLS itself (`tls_cert` + `tls_key`) tells the app so, and a socket
  195. without a proxy header still knows its peer:
  196. - every request object has `secure` — `true` when the request came over this server's TLS,
  197. `false` on plain HTTP (next to the existing `remoteAddress`, `"a.b.c.d"` or null).
  198. - the WebSocket `connect` event carries `ip` (the peer's address, same `"a.b.c.d"` text as
  199. `remoteAddress`; `''` on the raw event when the kernel cannot say) and `secure`;
  200. `NativeWebSocketServer` hands them to the `WsClient` as `client.ip` (null if unknown) and
  201. `client.secure`.
  202. - WebSocket upgrades are plain-HTTP only (a TLS connection is never upgraded, same as SSE),
  203. so `client.secure` is always `false` today; an upgrade aimed at a TLS port is answered as an
  204. ordinary request with `req.secure == true`. A TLS-terminating front is still read from
  205. `X-Forwarded-Proto`.
  206. - hl:http2 / hl:http3 expose neither `remoteAddress` nor `secure` today; not added here.
  207. - Fixture: `tests/pass/plugins/056_http1_secure_ip.hl` (plain and TLS, self-signed cert made
  208. with openssl).
  209. ## Server-Sent Events (ticket #144)
  210. The push channel to an `EventSource` (or `curl -N`), imported by name like any other export —
  211. from a static, a method or a handler, the same way `spawnArgs` comes from `hl:proc`:
  212. ```hybriel
  213. import { sseStart, sseSend, sseBroadcast, sseAlive, sseCount } from 'hl:http1'
  214. static openEvents = (route, req) => { // an hl:web function route
  215. let conn = sseStart(req.respond) // the GET is now text/event-stream
  216. sseSend(conn, JSON.stringify({ hello = 1 })) // one `data:` frame to that client
  217. return null
  218. }
  219. ```
  220. ```
  221. sseStart(respond) // req.respond → the connection id, or null (already answered, or TLS)
  222. sseSend(conn, text) // `data: <text>` + blank line to one stream → true, or false when it is gone
  223. sseBroadcast(text) // the same frame to every open stream → how many got it
  224. sseAlive(conn) // still open? asks the registry, pushes nothing → Boolean
  225. sseClose(conn) // close one stream → true, or false when already gone
  226. sseCount() // how many streams are open now
  227. ```
  228. `sseStart` writes the 200 head (`Content-Type: text/event-stream`, `Cache-Control: no-cache`,
  229. `X-Accel-Buffering: no`) and `: connected`. A text with newlines continues the frame, so
  230. `json + newline + 'id: 42'` sends a data field and an id field. The registry (http1.zig, missions
  231. 031/080/084) keys a stream by a monotonic id, never the fd; a closed peer is reaped at once (FIN,
  232. EPOLLRDHUP) or at the next `:` heartbeat (every 5 s), after which `sseSend` answers false. Plain
  233. HTTP only: on this plugin's own TLS `sseStart` answers null — end TLS in a proxy.
  234. hl:http1 ships no browser half, so a file the browser build reaches (a lib a component imports)
  235. may import these too: each is bound there to a refusal that throws only if the browser calls it.
  236. - Regression test: `tests/core-ast/web-tickets.mjs 144` (a real client reads the frames a static
  237. and a method sent).
  238. ## The outgoing WebSocket client (ticket #109)
  239. Everything above is the SERVER half — a browser (or anything else) dialling in.
  240. `WebSocketClient` is the other direction: Hybriel dialling OUT to someone else's
  241. WebSocket server. Subclass it and answer its three events. A subclass does NOT inherit
  242. the parent's run body (same rule as `NativeHttpServer`/`NativeWebSocketServer`: a parent's
  243. own root never runs for it) — end your own file's root with `connect()`, exactly as those
  244. two end theirs with `listen()`:
  245. ```hybriel
  246. import { WebSocketClient } from 'hl:http1'
  247. inherit WebSocketClient
  248. String url = "wss://example.com/socket"
  249. Hybrid headers = { "Authorization" = "Bearer …" }
  250. on open() {
  251. send('hello')
  252. }
  253. on message(text) {
  254. console.log('got: ' + text)
  255. }
  256. on close(code) {
  257. console.log('closed: ' + code)
  258. }
  259. connect()
  260. ```
  261. Or attach handlers to an instance directly, without subclassing at all — the same
  262. `on instance.event(...)` form used throughout this plugin's own tests:
  263. ```hybriel
  264. import { WebSocketClient } from 'hl:http1'
  265. client = new WebSocketClient(url = 'ws://127.0.0.1:8091/')
  266. on client.open() { client.send('hello') }
  267. on client.message(text) { console.log('got: ' + text) }
  268. on client.close(code) { console.log('closed: ' + code) }
  269. ```
  270. ### Properties
  271. | Property | Type | Default | Description |
  272. |----------|------|---------|-------------|
  273. | `url` | String | `null` | `ws://host[:port][/path]` or `wss://…` |
  274. | `headers` | Object | `{}` | Extra headers sent on the Upgrade request |
  275. | `caFile` | String | `null` | `wss://` only — an EXTRA trust anchor for a self-signed fixture, exactly hl:fetch's field of the same name (never a replacement for the system trust store) |
  276. | `connected` | Boolean | `false` | True between `open` and `close` |
  277. ### Methods
  278. | Method | Answers | Description |
  279. |--------|---------|-------------|
  280. | `connect()` | `true`/`false` | Dial `url` (idempotent — a no-op while already dialling or open). The file root calls this for you. |
  281. | `send(text)` | `1`/`0` | One text frame to the peer; `0` when not open |
  282. | `close([code])` | `1`/`0` | Start the close handshake; `close` still fires once the peer's echo (or a timeout) completes it |
  283. ### Events
  284. ```
  285. emit open() // the connection is open and ready for send()
  286. emit message(String data) // one complete text (or binary) message
  287. emit close(Number code) // the connection ended — RFC 6455 §7.4 code
  288. ```
  289. At most one `open` ever precedes a `close`: a connection that never opened still gets
  290. exactly one `close` (`1006` for a dial that never reached a peer — DNS failure, refused,
  291. TLS handshake failure; `1002` for a handshake the peer answered but got wrong).
  292. ### `wss://` uses hl:fetch's TLS
  293. The client half of `plugins/http/tls_common.zig` — the SAME module hl:fetch uses for
  294. `https://`. The system trust store, hostname verification always on, and `caFile` for an
  295. extra anchor. There is no verify-off switch, on this client either.
  296. ### Ping/pong is automatic; reconnect never is
  297. A quiet connection is pinged after `HL_WS_PING_MS` and dropped if the pong doesn't land
  298. within `HL_WS_PONG_TIMEOUT_MS` — the SAME two env vars the server's liveness sweep reads
  299. (mission 091, above). Any inbound ping is answered with a pong immediately. Neither ever
  300. reaches `.hl`: the protocol requires both, and they are not application information.
  301. **Reconnect is never automatic.** A dropped connection reaches you as exactly one `close`
  302. event and nothing here dials again on its own — call `connect()` again yourself (typically
  303. from your own `on close`) if you want a reconnect policy; `connect()` after a `close` opens
  304. a fresh connection, it is not a one-shot object.
  305. ### Architecture
  306. One dedicated thread per connection — the same shape as hl:fetch's one-thread-per-ticket
  307. model, not the server's shared epoll pool: a client dials a handful of long-lived peers,
  308. not thousands of short ones, and a private thread means a private event queue with no risk
  309. of misdelivering one connection's frames onto another instance's `on open`/`on
  310. message`/`on close`. The thread does DNS + TCP connect, the TLS handshake for `wss://`, the
  311. HTTP Upgrade handshake, then a read loop over the shared RFC 6455 framing
  312. (`plugins/http/ws_common.zig`) — this side's own frames go out through
  313. `writeFrameMasked`/`writeCloseMasked` (RFC 6455 §5.1: "a client MUST mask all frames"),
  314. freshly masked per frame from the kernel CSPRNG.
  315. - Fixtures: `tests/pass/plugins/039_http1_ws_client.hl` (open, send, a server-pushed
  316. frame, close from the client) and
  317. `tests/pass/plugins/040_http1_ws_client_close_reconnect.hl` (close from the SERVER's
  318. side, and an explicit reconnect proving it is never automatic).
  319. ## Request caps (ticket #445)
  320. Both are options of `NativeHttpServer`, `NativeWebSocketServer` and `create_server`:
  321. - `Number maxBody = 20971520` — the largest request body read (default 20 MiB). A `Content-Length`
  322. above it is answered `413 Payload Too Large` + `Connection: close` BEFORE any of the body is read or
  323. allocated; a chunked body that grows past it is refused the same way. Raise it for apps taking
  324. bigger uploads (git pushes over http1).
  325. - `Boolean wsCheckOrigin = false` — refuse a WebSocket upgrade whose `Origin` is foreign with `403
  326. Forbidden` BEFORE the 101. Allowed: the Origin's authority equals the request's `Host`, or it is in
  327. `String wsOrigins` (comma-separated, `https://app.example.com` or a bare `app.example.com`). A request
  328. with NO `Origin` header (non-browser clients) is always let through; `Origin: null` is refused. Off by
  329. default so a proxy that rewrites `Host` cannot break existing deployments; hl:web may turn it on.
  330. hl:http2 / hl:http3: see the ticket-445 report in missions/445-http1-caps.md.
  331. `WsClient.path` is the raw upgrade request target, including the query string (for example `/channel?device=a%2Fb`); it is captured before the HTTP request is freed.

Branches

Latest commits

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