gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9b94aa6a9b94aa6aMerge branch 'f1b-cleanup' into mainIdent9b94aa6a/plugins/http1/README.md

18.1 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. ### WebSocket liveness sweep (mission 091)
  137. The WS reader loop (one thread, epoll, level-triggered EPOLLIN) already wakes on a 500ms
  138. timeout, so liveness costs no timer and no extra thread: on every tick it walks the
  139. upgraded sockets, pings the ones that have gone quiet, and drops the ones whose pong is
  140. overdue.
  141. A drop enqueues the **same `close` event a real FIN would have produced**, so every
  142. consumer above this plugin — hl:web's push subscription registry included — prunes through
  143. the path it already had. No new concept travels upward, and nothing at the `.hl` level
  144. needs a timer facility.
  145. Why it is needed: a peer that vanishes without closing (dead wifi, a suspended laptop, a
  146. host that never sent the FIN) leaves a socket that stays open and **writable**. A server
  147. with nothing to push at it never discovers the corpse, so before this the subscription was
  148. immortal. A closed tab is not this case — the browser's stack sends the FIN, and even under
  149. CDP offline emulation it still answers protocol pings (measured, mission 091), which is why
  150. the regression test's dead peer is a raw socket that goes silent rather than a tab.
  151. | Env var | Default | Meaning |
  152. |---------|---------|---------|
  153. | `HL_WS_PING_MS` | `15000` | a socket quiet this long is pinged |
  154. | `HL_WS_PONG_TIMEOUT_MS` | `10000` | a ping unanswered this long ⇒ the peer is gone |
  155. Read once when the engine starts; timeouts are measured on `CLOCK_MONOTONIC`, so an NTP
  156. step cannot make one fire early or never. Any inbound frame — of any opcode — counts as
  157. proof of life and clears an outstanding ping.
  158. - Regression test: `tests/browser/tests/23-ws-liveness-sweep.mjs` (includes the
  159. falsification: the same silent peer against a sweep-disabled server stays registered).
  160. ### The handshake's cookies + a cookie-grade random (mission 093)
  161. A WebSocket upgrade is an ordinary HTTP request, so the browser attaches the site's cookies
  162. to it. That is the one moment an upgraded socket can be attributed to whoever loaded the
  163. page — after the 101 the request and its headers are freed and the connection carries no
  164. identity of its own. The `connect` event therefore gained a sixth field:
  165. ```
  166. { kind, id, data, binary, code, cookie }
  167. ```
  168. `cookie` is the handshake's `Cookie:` header verbatim, non-empty on `connect` only. Nothing
  169. is parsed here: hl:web's session layer (`plugins/web/web_session.hl`) owns the cookie's name
  170. and meaning, and this plugin owns only its delivery.
  171. ```
  172. randomToken(Number n) // n lowercase hex chars, kernel CSPRNG (getrandom(2)), max 128
  173. ```
  174. A session id is the only thing between a stranger and someone else's session, so it may not
  175. come from a seeded PRNG — `hl:math`'s `random()` is a clock-seeded xoshiro whose state a
  176. handful of outputs reveals, which would make every other id derivable from one's own. This
  177. lives here because a session cookie is an HTTP artifact and this is the plugin that parses
  178. and writes one; it is currently the only CSPRNG reachable from `.hl`.
  179. - Regression test: `tests/browser/tests/25-sessions.mjs` (two real browser instances = two
  180. cookie jars = two sessions).
  181. Ticket #74 added `host` (the handshake's `Host:` header) and ticket #105 `headers`: every
  182. header of the handshake as `name: value` lines, names lowercase, non-empty on `connect` only.
  183. `NativeWebSocketServer` hands them to the `WsClient` as `client.headers`, a hash by name —
  184. which is where hl:web reads the headers a navigation over that socket is constructed with.
  185. ### TLS flag and peer address (hybriel#214)
  186. A server that terminates TLS itself (`tls_cert` + `tls_key`) tells the app so, and a socket
  187. without a proxy header still knows its peer:
  188. - every request object has `secure` — `true` when the request came over this server's TLS,
  189. `false` on plain HTTP (next to the existing `remoteAddress`, `"a.b.c.d"` or null).
  190. - the WebSocket `connect` event carries `ip` (the peer's address, same `"a.b.c.d"` text as
  191. `remoteAddress`; `''` on the raw event when the kernel cannot say) and `secure`;
  192. `NativeWebSocketServer` hands them to the `WsClient` as `client.ip` (null if unknown) and
  193. `client.secure`.
  194. - WebSocket upgrades are plain-HTTP only (a TLS connection is never upgraded, same as SSE),
  195. so `client.secure` is always `false` today; an upgrade aimed at a TLS port is answered as an
  196. ordinary request with `req.secure == true`. A TLS-terminating front is still read from
  197. `X-Forwarded-Proto`.
  198. - hl:http2 / hl:http3 expose neither `remoteAddress` nor `secure` today; not added here.
  199. - Fixture: `tests/pass/plugins/056_http1_secure_ip.hl` (plain and TLS, self-signed cert made
  200. with openssl).
  201. ## Server-Sent Events (ticket #144)
  202. The push channel to an `EventSource` (or `curl -N`), imported by name like any other export —
  203. from a static, a method or a handler, the same way `spawnArgs` comes from `hl:proc`:
  204. ```hybriel
  205. import { sseStart, sseSend, sseBroadcast, sseAlive, sseCount } from 'hl:http1'
  206. static openEvents = (route, req) => { // an hl:web function route
  207. let conn = sseStart(req.respond) // the GET is now text/event-stream
  208. sseSend(conn, JSON.stringify({ hello = 1 })) // one `data:` frame to that client
  209. return null
  210. }
  211. ```
  212. ```
  213. sseStart(respond) // req.respond → the connection id, or null (already answered, or TLS)
  214. sseSend(conn, text) // `data: <text>` + blank line to one stream → true, or false when it is gone
  215. sseBroadcast(text) // the same frame to every open stream → how many got it
  216. sseAlive(conn) // still open? asks the registry, pushes nothing → Boolean
  217. sseCount() // how many streams are open now
  218. ```
  219. `sseStart` writes the 200 head (`Content-Type: text/event-stream`, `Cache-Control: no-cache`,
  220. `X-Accel-Buffering: no`) and `: connected`. A text with newlines continues the frame, so
  221. `json + newline + 'id: 42'` sends a data field and an id field. The registry (http1.zig, missions
  222. 031/080/084) keys a stream by a monotonic id, never the fd; a closed peer is reaped at once (FIN,
  223. EPOLLRDHUP) or at the next `:` heartbeat (every 5 s), after which `sseSend` answers false. Plain
  224. HTTP only: on this plugin's own TLS `sseStart` answers null — end TLS in a proxy.
  225. hl:http1 ships no browser half, so a file the browser build reaches (a lib a component imports)
  226. may import these too: each is bound there to a refusal that throws only if the browser calls it.
  227. - Regression test: `tests/core-ast/web-tickets.mjs 144` (a real client reads the frames a static
  228. and a method sent).
  229. ## The outgoing WebSocket client (ticket #109)
  230. Everything above is the SERVER half — a browser (or anything else) dialling in.
  231. `WebSocketClient` is the other direction: Hybriel dialling OUT to someone else's
  232. WebSocket server. Subclass it and answer its three events. A subclass does NOT inherit
  233. the parent's run body (same rule as `NativeHttpServer`/`NativeWebSocketServer`: a parent's
  234. own root never runs for it) — end your own file's root with `connect()`, exactly as those
  235. two end theirs with `listen()`:
  236. ```hybriel
  237. import { WebSocketClient } from 'hl:http1'
  238. inherit WebSocketClient
  239. String url = "wss://example.com/socket"
  240. Hybrid headers = { "Authorization" = "Bearer …" }
  241. on open() {
  242. send('hello')
  243. }
  244. on message(text) {
  245. console.log('got: ' + text)
  246. }
  247. on close(code) {
  248. console.log('closed: ' + code)
  249. }
  250. connect()
  251. ```
  252. Or attach handlers to an instance directly, without subclassing at all — the same
  253. `on instance.event(...)` form used throughout this plugin's own tests:
  254. ```hybriel
  255. import { WebSocketClient } from 'hl:http1'
  256. client = new WebSocketClient(url = 'ws://127.0.0.1:8091/')
  257. on client.open() { client.send('hello') }
  258. on client.message(text) { console.log('got: ' + text) }
  259. on client.close(code) { console.log('closed: ' + code) }
  260. ```
  261. ### Properties
  262. | Property | Type | Default | Description |
  263. |----------|------|---------|-------------|
  264. | `url` | String | `null` | `ws://host[:port][/path]` or `wss://…` |
  265. | `headers` | Object | `{}` | Extra headers sent on the Upgrade request |
  266. | `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) |
  267. | `connected` | Boolean | `false` | True between `open` and `close` |
  268. ### Methods
  269. | Method | Answers | Description |
  270. |--------|---------|-------------|
  271. | `connect()` | `true`/`false` | Dial `url` (idempotent — a no-op while already dialling or open). The file root calls this for you. |
  272. | `send(text)` | `1`/`0` | One text frame to the peer; `0` when not open |
  273. | `close([code])` | `1`/`0` | Start the close handshake; `close` still fires once the peer's echo (or a timeout) completes it |
  274. ### Events
  275. ```
  276. emit open() // the connection is open and ready for send()
  277. emit message(String data) // one complete text (or binary) message
  278. emit close(Number code) // the connection ended — RFC 6455 §7.4 code
  279. ```
  280. At most one `open` ever precedes a `close`: a connection that never opened still gets
  281. exactly one `close` (`1006` for a dial that never reached a peer — DNS failure, refused,
  282. TLS handshake failure; `1002` for a handshake the peer answered but got wrong).
  283. ### `wss://` uses hl:fetch's TLS
  284. The client half of `plugins/http/tls_common.zig` — the SAME module hl:fetch uses for
  285. `https://`. The system trust store, hostname verification always on, and `caFile` for an
  286. extra anchor. There is no verify-off switch, on this client either.
  287. ### Ping/pong is automatic; reconnect never is
  288. A quiet connection is pinged after `HL_WS_PING_MS` and dropped if the pong doesn't land
  289. within `HL_WS_PONG_TIMEOUT_MS` — the SAME two env vars the server's liveness sweep reads
  290. (mission 091, above). Any inbound ping is answered with a pong immediately. Neither ever
  291. reaches `.hl`: the protocol requires both, and they are not application information.
  292. **Reconnect is never automatic.** A dropped connection reaches you as exactly one `close`
  293. event and nothing here dials again on its own — call `connect()` again yourself (typically
  294. from your own `on close`) if you want a reconnect policy; `connect()` after a `close` opens
  295. a fresh connection, it is not a one-shot object.
  296. ### Architecture
  297. One dedicated thread per connection — the same shape as hl:fetch's one-thread-per-ticket
  298. model, not the server's shared epoll pool: a client dials a handful of long-lived peers,
  299. not thousands of short ones, and a private thread means a private event queue with no risk
  300. of misdelivering one connection's frames onto another instance's `on open`/`on
  301. message`/`on close`. The thread does DNS + TCP connect, the TLS handshake for `wss://`, the
  302. HTTP Upgrade handshake, then a read loop over the shared RFC 6455 framing
  303. (`plugins/http/ws_common.zig`) — this side's own frames go out through
  304. `writeFrameMasked`/`writeCloseMasked` (RFC 6455 §5.1: "a client MUST mask all frames"),
  305. freshly masked per frame from the kernel CSPRNG.
  306. - Fixtures: `tests/pass/plugins/039_http1_ws_client.hl` (open, send, a server-pushed
  307. frame, close from the client) and
  308. `tests/pass/plugins/040_http1_ws_client_close_reconnect.hl` (close from the SERVER's
  309. side, and an explicit reconnect proving it is never automatic).
  310. ## Request caps (ticket #445)
  311. Both are options of `NativeHttpServer`, `NativeWebSocketServer` and `create_server`:
  312. - `Number maxBody = 20971520` — the largest request body read (default 20 MiB). A `Content-Length`
  313. above it is answered `413 Payload Too Large` + `Connection: close` BEFORE any of the body is read or
  314. allocated; a chunked body that grows past it is refused the same way. Raise it for apps taking
  315. bigger uploads (git pushes over http1).
  316. - `Boolean wsCheckOrigin = false` — refuse a WebSocket upgrade whose `Origin` is foreign with `403
  317. Forbidden` BEFORE the 101. Allowed: the Origin's authority equals the request's `Host`, or it is in
  318. `String wsOrigins` (comma-separated, `https://app.example.com` or a bare `app.example.com`). A request
  319. with NO `Origin` header (non-browser clients) is always let through; `Origin: null` is refused. Off by
  320. default so a proxy that rewrites `Host` cannot break existing deployments; hl:web may turn it on.
  321. hl:http2 / hl:http3: see the ticket-445 report in missions/445-http1-caps.md.

Branches

Latest commits

  • 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
  • edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
  • 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
  • c7eef14aMerge branch 'nv1-navigate' into mainIdent
  • 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
  • 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
  • 23971fb7ident#49: media queries in the language's @media formmre
  • 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
  • aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
  • ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre
  • dc6d486fident#27: the docs gate expects the new Access entry in the main menumre
  • d277633cident#27: README: identity access and the introspect endpointmre
  • e999b0d3ident#27: the Access tab — one key per identity for all its apps: give access in three steps, the overview matrix, a cell's sheet (since, last use, level, rotate, revoke), the app's check POST /api/introspect, agent identities hidden from the login picker, an inbox icon in the header's icon style (gate: tests/access.mjs)mre
  • 436206fcident#47: deploy.sh runs the sign-in gate on the deploy's own port slot, like the sessionwrites and docs gates (the default 8700 can be taken by another process)mre
  • a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mre
  • d8ec703dident#45: /docs shows docs/IDENT.md (hl:markdown, vendored from ac1ed9da), one Docs entry in the main menu, README for developers only, gates tests/docs.mjs and tests/sessionwrites.mjs in deploy.shmre
  • ec6aad35Merge branch 'a28g-amp-callsites' into d45-docsmre
  • 6bfbd3f2ident#45: docs/IDENT.md, what ident is and how it works; CONCEPT.md marks one id per app as droppedmre
  • c0edca26ident#28 A28G: write & at every call that hands a session to an &-parameter; gate tests/sessionwrites.mjs pins that sign-in, pending address, embed sign-in and selector land in the session filesmre
  • 80965c08ident#28: README says the deploy goes through the standbymre