gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb680c483b680c483Revert "gitoria#22: RepoTabs wrapping component for the repo tabs (active tab, no content for a missing repo)"mreb680c483/plugins/web/README.md

20.5 KB

  1. # hl:web — the web framework
  2. `hl:web` serves an app's pages from the server and keeps them live in the browser. It is written
  3. in Hybriel: `WebFramework.hl` is the server half, `client.hl` the browser half, and `compile.hl`
  4. turns each component's View into that component's own code. The model behind it (components,
  5. Views, realms, the boundary) is in [COMPONENTS.md](../../COMPONENTS.md). This page lists the rules
  6. an app is held to. Each rule is a located refusal at boot unless it says otherwise.
  7. ## Starting an app
  8. ```hybriel
  9. import WebFramework from 'hl:web'
  10. import Home from './components/home.hl'
  11. import Styles from './styles.hl'
  12. routes = [ { pattern = "/" component = Home } ]
  13. server = new WebFramework(routes = routes, styles = Styles, port = 8080)
  14. ```
  15. Settings may be passed as named arguments. Most of them may instead be members of the file that
  16. runs the `new`:
  17. | setting | default | meaning |
  18. |---|---|---|
  19. | `routes` | `[]` | the route table (below); pass it as an argument |
  20. | `styles` | none | the app's styles file: the imported class, or a path string. It must be in the project graph |
  21. | `port` | 8080 | the port to listen on |
  22. | `host` | `HL_HOST`/`HOST`, else 0.0.0.0 | the interface to bind |
  23. | `audience` | `{}` | per outward event, who receives it (see Events) |
  24. | `minify` | false | one-line HTML and compact modules |
  25. | `watchMode` | true | a saved `.hl` file re-analyses the app and reloads every open tab |
  26. | `sessionDir` | `<app>/.sessions` | where sessions are stored; `false` keeps them in memory |
  27. | `sessionMaxAge`, `sessionIdle`, `sweepInterval` | 14 days, 15 min, 5 min | the session clocks, in seconds |
  28. | `sessionCookie` | `hlsid` | the cookie's name: letters, digits, `-` and `_` |
  29. | `sessionSecure` | false | set the cookie's `Secure` flag (for an app behind https) |
  30. | `appTitle`, `appDescription`, `appImage`, `appFavicon`, `meta` | none | the head every page gets unless it declares its own |
  31. | `links` | none | a list of hybrids, one `<link>` each in every page's head (`{ rel = 'preconnect' href = '…' }`) |
  32. | `appIcons`, `appShortName`, `appThemeColor`, `appBackgroundColor`, `appTouchIcon`, `appManifest` | none | make the app installable: a web app manifest, linked from every head (see Offline and installable) |
  33. | `offline` | none | the pages kept offline: a service worker, their state in IndexedDB, a queue for their emits |
  34. | `pingEvery`, `pongWithin` | 25, 10 | the dead-socket clock, in seconds: the browser pings every `pingEvery`, and a pong missing after `pongWithin` closes the socket and reconnects |
  35. | `uploadMax` | 1 GiB | the largest file an emit may carry, in bytes (see Files in an emit) |
  36. | `pushKept`, `pushKeptBytes`, `tabKept` | 10000, 1 MiB, 600 | the push log per tab (see Events): the pushes kept for a socket that comes back, their bytes, and the seconds a tab without a socket is kept |
  37. An app runs on one web framework. If its files reach two packages that hold a `WebFramework.hl`
  38. (for example an old vendored copy beside this one), it is refused at boot, naming the import row
  39. of each.
  40. ## Routes
  41. Each entry has a `pattern` (`/posts/:id`, `/assets/*`) and one kind:
  42. | kind | answers with |
  43. |---|---|
  44. | `component = Home` or `"./components/home.hl"` | the page, rendered on the server; the component must be imported by the app, and must declare a View |
  45. | `function = (route, req) => { … }` | what the function returns (a Hybrid becomes JSON); `req.session` is the cookie's session, or null |
  46. | `direct = "text"` | that text |
  47. | `file = "./x"` | one file |
  48. | `directory = "./assets"` | the files under a directory |
  49. A named group (`:id`) reaches the component as a construction argument of the same name: declare
  50. `id = null` at its root. A named wildcard does the same with the rest of the path:
  51. `/code/*path` gives `path = 'src/lib/util.hl'` for `/code/src/lib/util.hl`, on the first load and
  52. on a navigation. A bare `*` has no name a member could take; it is what a `directory` route
  53. serves from.
  54. The request itself reaches a component the same way, and only one that declares the member
  55. (COMPONENTS.md): `session = null` gets the session, `host = null` the host without its port,
  56. `headers = null` the request's headers as a hash with lowercase names —
  57. `headers['accept-language']`. On a client navigation they are the headers of the request the
  58. navigation crossed on, so they are still the browser's own: the socket's upgrade request, or the
  59. `POST /__hl/emit` under the fallback. `cookie`, `authorization` and `proxy-authorization` are left
  60. out, because a member is state and state reaches page script.
  61. ## Components
  62. A component is a `.hl` file with a `View`. Its root members are its state, and are constructed on
  63. the server for each request.
  64. **A View attribute is a literal, a member or a field path.** `href = "/"`, `href = url` and
  65. `href = p.url` are allowed. `href = '/posts/' + id` is refused at its line: declare
  66. `postUrl = '/posts/' + id` at the file's root and write `href = postUrl`. The same holds for a
  67. value bound on a component reference (`Card { title = t }`) and for the condition of an `if` in a
  68. View, which may also be a `for` row variable.
  69. **An attribute name that is not an identifier is quoted.** `"aria-hidden" = "true"` and
  70. `"data-page" = it.target` render as written and bind like any attribute, in a `for` row too. A
  71. camelCase name is not rewritten (`ariaHidden` renders as `ariaHidden`). `data-page = it.target`
  72. unquoted is refused at its line, naming the quoted form.
  73. **A bound attribute in a `for` row follows the row** on every update of the list: a new list, a
  74. `push`, an `upsert` and a write into a row's record (`items[0].title = …`) repaint it, as they
  75. repaint the row's text and class.
  76. **The tree carries the elements the HTML parser implies.** `table { tr { td { … } } }` is rendered
  77. as `table > tbody > tr > td`, because that is the tree the browser builds from the HTML, and the
  78. page is continued from the tree the browser built. The pairs are listed in `view.hl`
  79. (`impliedElements`): `tr`, `td` and `th` under `table` get a `tbody`, `td` and `th` under `tbody`,
  80. `thead` or `tfoot` get a `tr`, and `col` gets a `colgroup`. Consecutive children that need the same
  81. container share one.
  82. The other rules:
  83. - A View reads only names the file declares. A name it declares nowhere is refused.
  84. - `parent './main.hl'` wraps a page in a shell. The shell declares `slot = null` and places
  85. `slot` in its View exactly once. A component that is filled (`Card { p { … } }`) must declare a
  86. slot too.
  87. - `body { … }` is allowed only as the root of a View, and a page wrapped by a parent cannot have
  88. one: the shell owns the body.
  89. - A View cannot render itself, directly or through other components.
  90. - A Style rule cannot be written on a component reference. Write it on an element inside that
  91. component.
  92. - A page's head comes from its members `__title`, `__description`, `__image`, `__favicon` and
  93. `__meta`, and falls back to the app's `appTitle`, `appDescription`, `appImage`, `appFavicon` and
  94. `meta`. A handler that writes one of them updates the document.
  95. ## Events
  96. `on name(…)` handlers and `emit` statements cross between the browser and the server over a
  97. WebSocket on the app's own port. `POST /__hl/emit` is the fallback for a peer without a socket.
  98. A handler that takes `session` as its last parameter gets the connection's session from the
  99. server, never from the peer.
  100. An outward event reaches the tab that caused it. To send it to other connections, give it an
  101. `audience` entry: a function of the event's arguments and the receiving connection's session that
  102. answers true or false.
  103. **No push is lost across a socket gap** (ticket #143). A push goes to the tab, not to its
  104. socket: the server numbers every push to a tab and keeps the last `pushKept` of them (at most
  105. `pushKeptBytes`), also while the tab has no socket. The bytes bound is the one that governs: a
  106. busy server pushes hundreds of small frames in a few seconds, and a count bound below the bytes one
  107. turns a short gap into a resync (#160). A tab whose socket comes back (a phone
  108. that slept, a network switch, a socket the ping gave up on) names the last push it got in
  109. its `hello` and is sent the rest again, in order, each once. A gap longer than that log, a
  110. tab gone longer than `tabKept` seconds, or a server that restarted resyncs the tab instead:
  111. the server mounts its shell and page again and sends the members it derives itself (those
  112. that call an imported class, and `session`), which the browser lays over the page. Then
  113. every mounted component that declares `on client reconnected(r)` gets
  114. `r = { how, missed, build, stale }`: `how` is `'replayed'` (nothing was lost; `missed` pushes came again)
  115. or `'resynced'` (a member only a push handler builds up may lack what was pushed meanwhile —
  116. ask the server for it here). `build` is the server's build and `stale` is true when it is not
  117. the build this page was rendered by — the server restarted onto changed sources (ticket #152;
  118. in every mode, `watchMode` additionally reloads the tab itself). It fires once per reopened
  119. socket, never on the first.
  120. ```hybriel
  121. on client reconnected(r) {
  122. if (r.stale) { location.reload() }
  123. if (r.how == 'resynced') { refresh() }
  124. }
  125. ```
  126. A value-form emit (`answer = emit server ask()`) waits for one answer, so it has one answerer.
  127. If two files in the target realm answer the event, it is refused.
  128. **A write anywhere repaints what it wrote** (tickets #98, #99), from the compiler's write
  129. sets, never by watching the members:
  130. - A listener repaints what its handler writes when the handler is done. A handler still
  131. waiting after the task that started it (a network answer, `new Promise(…)`) has its
  132. write set painted then too, so what it wrote before the wait shows while it waits.
  133. - A function made inside a component — an `XMLHttpRequest`'s `onload` or `onprogress`, a
  134. timer, a Promise's executor, a `then` — is compiled so that every return of it is
  135. announced with the site it was made at. What it writes (a member, a push into one, a
  136. field inside one, and what the methods it calls and the events it emits write) is
  137. repainted after the task that ran it. A function that writes no member repaints nothing.
  138. - A repaint the listener already made in the same task is not made twice.
  139. **After a face that takes `session`** (tickets #121, #122), the server re-derives the
  140. members that read `session` for the tabs that mounted the component, with the page's own
  141. route params, and ships them in the ack (`sync`); the browser takes them as writes.
  142. - A member that reads `session` and calls an imported class, directly or through a local
  143. method or static, is computed on the server only and never re-derived in the browser.
  144. - Such a member is already up to date when the handler continues, so a client handler that
  145. appends the face's returned row to a list derived from `session` shows it twice. Assign
  146. from what the sync brought, or leave the list to the sync.
  147. - A member derived from `session` that needs a server-only resource (a database) must reach
  148. it through an imported class or a static of one; a plain copy (`me = session.user.id`) is
  149. derived everywhere.
  150. ### Files in an emit
  151. A browser `File` (an input's `ev.target.files[0]`, a dropped file) or a list of them
  152. (`ev.target.files`) may be an argument of an `emit server …`. It never rides the socket:
  153. before the emit goes out, the client half sends each file to `/__hl/upload` as its own HTTP
  154. requests, with the page's session cookie, in parts of 1 MiB. The face gets the file in its
  155. place as `{ bytes, name, type, size }` (`bytes` a `Bytes`), or a list of those for a list:
  156. ```hybriel
  157. input { type = 'file' on change(ev) { emit send(ev) } }
  158. on send(ev) { saved = emit server saveFile(ev.target.files[0]) }
  159. on server saveFile(file) {
  160. writeFile('uploads/' + file.name, file.bytes)
  161. return file.size
  162. }
  163. ```
  164. - **Progress.** While a file is sent, every mounted component that declares
  165. `on client uploadProgress(p)` gets `p = { event, index, name, sent, size }`: the emit's
  166. event, the file's position among the emit's files, its name, the bytes sent so far and
  167. its size.
  168. - **A dropped connection.** A part that did not come back is asked for again: the client
  169. waits (250 ms, doubling up to 4 s), asks the server how much of the file it has, and goes
  170. on from there. After 8 drops in a row it gives up.
  171. - **A failed upload ends the emit.** A file the server refuses (bigger than `uploadMax`, an
  172. upload of another session) or a connection that stays down ends the emit with that error
  173. instead of sending it — except a queueable emit in an offline app, which is queued with its
  174. files when the connection is what failed (COMPONENTS §10): it gets the failed ack a failing face sends
  175. (`{ t: 'ack', i, ok: false, error }`), so a value-form emit answers null and the error is
  176. logged. The face does not run.
  177. - An upload belongs to the session that started it, and one emit takes it. An upload that
  178. nothing takes within an hour is dropped. The parts are held in the server's memory until
  179. the emit takes them.
  180. ## Offline and installable
  181. The full model is [COMPONENTS.md §10](../../COMPONENTS.md). An app writes no JavaScript for any
  182. of it.
  183. ```hybriel
  184. appTitle = "Hybriel Notes"
  185. appIcons = [ { src = "/static/icon-192.png" sizes = "192x192" } { src = "/static/icon-512.png" sizes = "512x512" } ]
  186. offline = [ NoteList, NoteEditor ]
  187. ```
  188. - `appIcons` (or `appManifest`, or `offline`) serves `/__hl/manifest.webmanifest` and links it,
  189. with an apple-touch-icon, from every page's head. `appManifest`'s entries are written over the
  190. generated manifest.
  191. - `offline` lists pages: route components, as classes or path strings. Anything else is refused
  192. at its line. The framework generates the service worker and registers it. The shell and the
  193. listed pages' documents are cached, and a navigation is network-first. What the server last
  194. said about a listed page is kept in IndexedDB and shown over an older cached document. A
  195. statement-form `emit server …` from a listed page that does not reach the server is queued and
  196. replayed in order when the socket reopens. Each queued emit carries a stable id, and the
  197. server runs it once: a replay whose ack was lost is answered again without running the handler
  198. (the last 200 ids per session are kept). A socket that goes silent without closing is noticed
  199. by the ping and reopened. A queued emit keeps its files: IndexedDB holds them with the entry,
  200. and they go up on the replay under the emit's id, once (COMPONENTS §10). A page that
  201. declares `__hlQueued = 0` /
  202. `__hlQueue = []` shows the queue. A page that declares `__hlOnline = true` has it follow the browser's
  203. connection (`navigator.onLine`, and the online/offline events), so a View can say "you are offline".
  204. - `offlineFallback = Start` (a route component, class or path string, answered by a route with no
  205. parameter; needs `offline`) names a DATA-FREE page: the worker keeps its document once, fetched without
  206. credentials, and shows it for any page it has nothing for while the network is down, instead of "Unavailable
  207. offline". Not set: nothing changes. A page (kept or the fallback) that declares `__hlDataFree = true` is kept
  208. the same way — its document is the anonymous one, and the browser keeps neither its state nor a queue for it.
  209. - Kept state is per component for a member no route parameter feeds (the same list at every url of
  210. the page), per url for the rest. A param page that was never loaded as a document is answered offline
  211. with a kept document of the same component, booted with the url's parameters.
  212. - What is kept belongs to the last user who was logged in. An expired or fresh anonymous session
  213. changes nothing: that user's queue is held, and replays when the same user logs in again (the server
  214. refuses a replay made for another user). Another user logging in forgets the copy (state, queue and the
  215. worker's documents); an entry from before users were kept is dropped unsent. A
  216. face that logs the session out forgets the copy by itself (the ack says whose session it is now);
  217. an app with its own logout calls `forgetOffline()` from `hl:web`.
  218. - In any app, an emit in flight when its socket closes is sent again with its id over the POST
  219. fallback or the next socket, and answered there (ticket #107). A page being left
  220. (`beforeunload`, `pagehide`) reopens nothing and posts nothing.
  221. - `import { notify, notifyAt, notifyIn } from 'hl:web'` shows a notification now, or at a time while the page
  222. is open. A closed app cannot be woken at a set time without a server push.
  223. ## What it serves
  224. | url | what |
  225. |---|---|
  226. | `/<file key>` (e.g. `/components/home.hl`) | a component's browser module |
  227. | `/__hl/hl-runtime.js` | the runtime every module imports |
  228. | `/__hl/web/client.js` | this package's browser half (other packages' halves are at `/__hl/<name>/client.js`) |
  229. | `/__hl/app.css` | the one stylesheet, built from the styles file and every component's `Style` |
  230. | `/__hl/emit` | the POST fallback for emits |
  231. | `/__hl/up` | an empty `204`: the probe a tab makes once a second while its socket waits to reconnect, so it is back within about a second of a restarted server (ticket #153; the backoff between socket attempts stops at 4 s) |
  232. | `/__hl/manifest.webmanifest` | the web app manifest, for an installable app |
  233. | `/__hl/sw.js`, `/__hl/web/worker.js` | the service worker's entry script and its compiled module, for an app with `offline` |
  234. | `/__hl/upload` | a file of an emit, in parts (`POST` `{ name, type, size, q, n }` → `{ id, have }`, or `{ handled }` when the session handled emit `q` already; `POST ?id=&at=` one part → `{ have }`; `GET ?id=` → `{ have }`) |
  235. The page loads the modules and the stylesheet as `<url>?v=<hash>`, where the hash covers everything the build serves. A url with the current hash is sent with `Cache-Control: public, max-age=31536000, immutable`, and any other url with `no-cache`. A deploy therefore changes every url, and a tab that navigates into a newer build loads that page as a full document.
  236. An app's own `file` and `directory` routes keep the same url across deploys, so they answer with an `ETag` of the content and `Cache-Control: no-cache` (a route's own `Cache-Control` header replaces that). A request whose `If-None-Match` names the current tag gets a `304` with no body.
  237. ## Cloned row templates: measured, not adopted (ticket #68)
  238. Svelte clones one hoisted `<template>` per row or branch shape; hl:web builds a browser-created row element by element. Measured with `tests/browser/bench-web-rows.mjs` (headless Chrome, a clean page before every run, best of 5, ms, master c183052c):
  239. | case | ms |
  240. |---|---|
  241. | replace 1000 rows (li, 3 elements, an `if` inside) | 338 |
  242. | append 10 x 100 rows (same row) | 780 |
  243. | deep row, 20 elements x 300 rows | 7.5 |
  244. | shallow row, 2 elements x 1000 rows | 14 |
  245. | toggle an `if` branch 1000 times | 45 |
  246. DOM creation is not where the time goes: the CPU profile (`HL_BENCH_PROF=<case>`) puts `createElement`, `setAttribute` and `appendChild` together under 3% of the cheap cases and the dearer cases are bound by something else. A 20-element row costs 25 us per row in total, a 2-element row 14 us; cloning could not make either 1.2x faster, and the machinery that wires sites, events and marks onto a clone is the same code the walk runs today (a claim walk over the clone), so nothing is saved there either. No prototype was built: the bound from the profile is under 1.03x.
  247. What the profile does show: the 3-element row with an `if` costs 340 us, and 115 ms of its 340 is `rehome` -> `sitesOnto`, which scans the mount's WHOLE `m.sites` for every row built and copies each site it reads (value semantics), so a build of n rows is O(n x sites). The append case is worse (780 ms) for the same reason plus `updateRow` on the rows that stay. That is the cost to attack, not element creation.
  248. ### The fix that followed (ticket #68, second step)
  249. `sitesOnto` now reads `m.sites` from the end, stops at the first site older than the walk's, and writes `el` in place instead of copying each site. `rebindRow` decides once per row body whether it composes a child (nothing to take again if not) instead of copying the seed's tree for every row that stays, and `rowPaint` reads its paint entry in place (`paintEntry`) instead of copying the compiled table. Same bench, old (c183052c) vs new, best of 5, ms:
  250. | case | old | new | ratio |
  251. |---|---|---|---|
  252. | replace 1000 rows | 342.0 | 20.0 | 17.1x |
  253. | append 10 x 100 rows | 782.3 | 92.6 | 8.5x |
  254. | deep row 20 el x 300 | 8.4 | 7.6 | 1.1x |
  255. | shallow row 2 el x 1000 | 18.2 | 13.1 | 1.4x |
  256. | toggle if-branch x 1000 | 48.8 | 40.2 | 1.2x (noise: 0.98x to 1.2x across runs) |
  257. Typing in a routger chat (a copy of the app, 30 keystrokes, main-thread time) is unchanged at about 1.5 ms per key: a keystroke builds no rows. Gates: `HL_WEB_STRICT=1` framework browser test 398 ok, `tests/core-ast/web-tickets.mjs` 205 ok.

Branches

Latest commits

  • b680c483Revert "gitoria#22: RepoTabs wrapping component for the repo tabs (active tab, no content for a missing repo)"mre
  • 4fda244fgitoria#22: RepoTabs wrapping component for the repo tabs (active tab, no content for a missing repo)mre
  • 0fd5e280mission brief 004mre
  • e1d425e7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • e59ff114deploy.sh: wait up to DEPLOY_URL_WAIT (120 s) for 200 after the restart, as the other apps (cold compile, hybriel#148)mre
  • bcafcceb003: compose cache volume + tmpfs /tmp, gate start waits 120 s, report/LOG/STATUSmre
  • bed3f2d5Re-vendor Hybriel to the shared static build 0f396652 (plugins; bin/ is git-ignored)mre
  • 3207e128mission brief 003mre
  • 18ab71fbtests/ticketskit: wait up to 120 s for tickets (native Hybriel cold compile ~25 s, hybriel#148)mre
  • 4fffa966docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 4f47843egate: ticket links use the tickets short URL (/<slug>/<n>, tickets#25)mre
  • 86605446mission 002 (code order) 4/4: README file map + import order + 'Same output' test + gate run with a tickets HEAD copy, STATUS (entry, lessons), LOG, report; tests/realdata-baseline.mjs + realdata-compare.py (a cleanup answers the same on live data: pages, modules, API, git over HTTPS and SSH, faces), tests/letcount.pymre
  • cc7bf7bamission 002 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (289 lets → plain declarations; 213 left: 125 reassigned, 88 loop-bound; no member/import/param clash). gates 200/0, 46/0, 44/0; real-data reads + writes identical (browser modules: var → const only)mre
  • 090a20c6mission 002 (code order) 2/4: one lib/ file per topic — git.hl split into git (calls, branches, init, temp folder) / homepage / code / pulls / releases (+ git-helpers: paths, ids, |||PR/|||RL markers); repos-helpers, tickets-helpers, transport-helpers; util.hl = localtime + env, storage dir, addresses, lists, text checks, one newest-first sort (was 3 copies); the function routes out of project.hl into lib/api.hl (thin; plumbing in api-helpers.hl), sshgate.hl folded into api.hl + sshkeys.hl keyLine + repos.hl mayPush; 'Make main' and the merge answer out of the faces (code.hl makeMain, pulls.hl pullsView), one login helper (users.hl userOfLoginCode); project.hl is the map. Session-writing routes get &req + &server.sessions. gates 200/0, 46/0, 44/0; real-data identical except /login/failed now shows the parked reason for a browser that already had a session (the old copy-of-req lost it)mre
  • 110c2799mission 002 (code order) 1/4: .hl files out of the root — lib/ (api, git, localtime, markdown, repos, sshgate, sshkeys, tickets, tokens, transport, users), components/styles.hl; jsoncheck.hl removed (imported nowhere); import paths only. gates 200/0, 46/0, 44/0; real-data reads + writes identicalmre
  • fdfb4b1bgitoria: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gates 200/0, 46/0, 44/0mre
  • 5b46ac84antcolony#40: LOG.md — missions 069/072 are antcolony missions (report paths on Byrodin)mre
  • 5602ff41gitoria: Hybriel master 190aa11d (fc838894 GC correctness, #127 mountKids by reference, #126, #48) — tracker README flat; gates 200/0, 46/0, 44/0mre
  • e85eaf01gitoria: 069 round 2 — hybriel 1a096ad3 not adopted (Markdown SSR still grows); browser gate waits for the server-side logout before restartmre
  • 09ce4f3fgitoria: mission 069 re-vendor hybriel 8efba065 stopped (big SSR pages grow + slow down); lambda audit clean; old vendor keptmre