gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit4e0186784e018678|||PR deploy.sh: gates use Tracker's ports 8716-8719 and LC_ALL=C; README: 2 backups keptTracker4e018678/plugins/web/worker.hl

10.6 KB

  1. // The framework's SERVICE WORKER (COMPONENTS §10, D38) — the offline shell. It exists
  2. // only for an app that declares `offline = [ … ]`: hl:web compiles this file like
  3. // client.hl, serves it at /__hl/web/worker.js, and registers the entry script
  4. // /__hl/sw.js, which imports it and constructs it ONCE with the table below.
  5. //
  6. // WHAT IS KEPT IS THE APP'S DECISION (D38). `precache` holds the shared shell —
  7. // the runtime, the client half, the stylesheet, every page module, the web app
  8. // manifest and its icons — plus the DOCUMENT of each param-free route whose
  9. // component the allow-list names. `routes` is the client's route table with
  10. // `keep` on the rows the allow-list names, so a param-bearing page (`/notes/:id`)
  11. // is kept when it is VISITED, and only then. Every other page is unavailable
  12. // offline, and says so.
  13. //
  14. // THREE RULES, the ones the old hl:web ran (mission 101):
  15. // · a NAVIGATION is network-first. The network is the truth while it answers,
  16. // and a fresh document for a kept page replaces the cached one on the way past;
  17. // the cache is what an outage falls back to.
  18. // · a precached asset is cache-first. Its url carries the build's hash, so a hit
  19. // cannot be stale.
  20. // · everything else goes to the network untouched: the emit channel, a function
  21. // route, an app's own file. The socket never reaches a worker at all.
  22. //
  23. // WHY THE ENTRY SCRIPT IS NOT THIS FILE. A worker must add its listeners while its
  24. // script is first evaluated, and a `fetch` listener must hand `respondWith` its
  25. // promise before the listener returns. Every call in this language is awaited, so
  26. // neither can be written here; /__hl/sw.js does exactly those two things and calls
  27. // the methods below for everything else (WebFramework.hl, `workerEntry`).
  28. import HlwRouter from './router.hl'
  29. cfgText = '' // the table, as JSON text (the one construction argument)
  30. cfg = JSON.parse(cfgText)
  31. router = new HlwRouter(routes = cfg.routes)
  32. // INSTALL: the shell into this build's cache, one url at a time — a single failed
  33. // url must not throw the whole install away and leave the app with no shell
  34. install() {
  35. let cache = globalThis.caches.open(cfg.cache)
  36. for (url of cfg.precache) {
  37. // a data-free page is fetched as nobody: its document carries no user's state (#120)
  38. let creds = cfg.dataFree.includes(url) ? 'omit' : 'same-origin'
  39. let r = globalThis.__hlAttempt(() => { return fetch(url, { cache = 'reload' credentials = creds }) })
  40. if (r.ok && r.value.ok) { cache.put(url, r.value) }
  41. }
  42. globalThis.skipWaiting()
  43. return null
  44. }
  45. // ACTIVATE: the cache name carries the build's hash, so every other hl cache is an
  46. // older deploy's. This worker then controls the pages that are already open.
  47. activate() {
  48. for (name of globalThis.caches.keys()) {
  49. if (name != cfg.cache && name.startsWith('hl-shell-')) { globalThis.caches.delete(name) }
  50. }
  51. globalThis.clients.claim()
  52. return null
  53. }
  54. // FETCH: what answers this request. Never null — the entry script hands the answer to
  55. // `respondWith` unread.
  56. answer(req) {
  57. if (cfg.shell == false) { return fetch(req) }
  58. if (req.method != 'GET') { return fetch(req) }
  59. let url = new URL(req.url)
  60. if (url.origin != globalThis.location.origin) { return fetch(req) }
  61. if (req.mode == 'navigate') { return navigation(req, url) }
  62. if (cfg.precache.includes(url.pathname + url.search)) { return cacheFirst(req, url.pathname + url.search) }
  63. return fetch(req)
  64. }
  65. // may the document at this path be kept? Only if the route that answers it is a page
  66. // the allow-list names — the whole of D38 in one predicate
  67. kept(path) {
  68. let m = router.match(path)
  69. return m != null && m.route.keep == true
  70. }
  71. // HOW LONG A NAVIGATION WAITS FOR THE NETWORK when a kept copy of the page exists (#340), in ms.
  72. // A silent connection (no answer, no refusal) would otherwise show nothing at all. After this the
  73. // copy is served and the fetch goes on in the background; if it succeeds it refreshes the copy
  74. // (the page already shown stays). A page with no copy, or not kept, waits for the network.
  75. navWait = 1500
  76. navigation(req, url) {
  77. path = url.pathname + url.search
  78. let copy = null
  79. if (kept(url.pathname)) {
  80. copy = globalThis.caches.match(path, { cacheName = cfg.cache })
  81. if (copy == null) { copy = standIn(url.pathname) }
  82. }
  83. let r = null
  84. if (copy != null) {
  85. r = globalThis.__hlWithin(() => { return fetch(req) }, navWait, (late) => {
  86. if (late.ok && late.value.ok && !cfg.dataFree.includes(url.pathname)) { keep(path, late.value.clone()) }
  87. return null
  88. })
  89. if (r.late == true) { return marked(copy) }
  90. } else {
  91. r = globalThis.__hlAttempt(() => { return fetch(req) })
  92. }
  93. if (r.ok) {
  94. // a data-free page's copy is the anonymous one made at install, never the live render
  95. if (r.value.ok && kept(url.pathname) && !cfg.dataFree.includes(url.pathname)) { keep(url.pathname + url.search, r.value.clone()) }
  96. return r.value
  97. }
  98. let hit = globalThis.caches.match(url.pathname + url.search, { cacheName = cfg.cache })
  99. if (hit != null) { return marked(hit) }
  100. // A PAGE OF A KEPT COMPONENT THAT WAS NEVER LOADED AS A DOCUMENT (#124): any kept document
  101. // of the same component stands in — the page boots it with this url's parameters
  102. let like = standIn(url.pathname)
  103. if (like != null) { return marked(like) }
  104. // THE APP'S OWN FALLBACK (#120): a data-free page, kept once, instead of the bare notice
  105. if (cfg.fallback != null) {
  106. let fb = globalThis.caches.match(cfg.fallback, { cacheName = cfg.cache })
  107. if (fb != null) { return fb }
  108. }
  109. return unavailable(url.pathname)
  110. }
  111. // A DOCUMENT FROM THE CACHE SAYS SO (#342). It is as old as its visit, so the page must catch up when its
  112. // first socket opens: `"cached":true` goes first into the seed, and the client's first hello asks as a
  113. // reconnect does (`again`), which the server answers with the #143 resync. A document the network
  114. // rendered is never marked, so it never resyncs. The stored copy stays as it was.
  115. marked(res) {
  116. R = globalThis.Response
  117. H = globalThis.Headers
  118. tag = 'id="hl-seed">{'
  119. text = res.text()
  120. h = new H(res.headers)
  121. h.delete('content-length')
  122. h.delete('content-encoding')
  123. let out = text
  124. if (text.includes(tag) && !text.includes(tag + '}')) { out = text.replace(tag, tag + '"cached":true,') }
  125. return new R(out, { status = res.status statusText = res.statusText headers = h })
  126. }
  127. // a kept document of the route's own component: this route's first, else another route's
  128. standIn(path) {
  129. let m = router.match(path)
  130. if (m == null || m.route.keep != true) { return null }
  131. let cache = globalThis.caches.open(cfg.cache)
  132. let other = null
  133. for (req of cache.keys()) {
  134. let o = router.match(new URL(req.url).pathname)
  135. if (o != null && o.route.keep == true && o.route.page == m.route.page) {
  136. if (o.index == m.index) { return cache.match(req) }
  137. if (other == null) { other = req }
  138. }
  139. }
  140. return other != null ? cache.match(other) : null
  141. }
  142. keep(key, res) {
  143. let cache = globalThis.caches.open(cfg.cache)
  144. cache.put(key, res)
  145. return null
  146. }
  147. // CACHE-FIRST for the shell. A miss still asks the network, so a worker installed
  148. // before an asset existed is not a permanent failure.
  149. cacheFirst(req, key) {
  150. let hit = globalThis.caches.match(key, { cacheName = cfg.cache })
  151. if (hit != null) { return hit }
  152. let r = globalThis.__hlAttempt(() => { return fetch(req) })
  153. if (r.ok) {
  154. if (r.value.ok) { keep(key, r.value.clone()) }
  155. return r.value
  156. }
  157. let R = globalThis.Response
  158. return new R('', { status = 503 statusText = 'Offline' })
  159. }
  160. // A MESSAGE FROM A PAGE. `keep`: a page the browser reached by a client-side
  161. // navigation was never a document request, so the client asks for it to be kept —
  162. // fetched here as the document it would be, if it is a page the allow-list names.
  163. message(data) {
  164. if (data != null && data.t == 'forget') { return forget(data.path) }
  165. if (data == null || data.t != 'keep' || !kept(data.path) || cfg.dataFree.includes(data.path)) { return null }
  166. let r = globalThis.__hlAttempt(() => { return fetch(data.path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })
  167. if (r.ok && r.value.ok) { keep(data.path, r.value) }
  168. return null
  169. }
  170. // THE USER CHANGED (#125): every kept document is another user's, so they all go; the
  171. // page that stands is fetched again as the new session sees it
  172. forget(path) {
  173. let cache = globalThis.caches.open(cfg.cache)
  174. for (req of cache.keys()) {
  175. let u = new URL(req.url)
  176. if (kept(u.pathname) && !cfg.dataFree.includes(u.pathname)) { cache.delete(req) }
  177. }
  178. if (path != null && kept(path) && !cfg.dataFree.includes(path)) {
  179. let r = globalThis.__hlAttempt(() => { return fetch(path, { credentials = 'same-origin' headers = { 'Accept' = 'text/html' } }) })
  180. if (r.ok && r.value.ok) { keep(path, r.value) }
  181. }
  182. return null
  183. }
  184. // A NOTIFICATION WAS CLICKED: the app's open window is focused, or one is opened at
  185. // the path the notification carries
  186. clicked(n) {
  187. n.close()
  188. let path = n.data != null && n.data.path != null ? n.data.path : '/'
  189. for (c of globalThis.clients.matchAll({ type = 'window' includeUncontrolled = true })) {
  190. if (c.focus != null) { return c.focus() }
  191. }
  192. return globalThis.clients.openWindow(path)
  193. }
  194. // A PUSH ARRIVED (#173): the payload is JSON text — `{ title, body, url, tag }` — and is shown as a
  195. // notification by this worker, whether or not any page is open. `url` is where a click goes (the
  196. // path rides in the notification's data, `clicked` reads it); a payload that is not JSON is
  197. // shown as the body of a notification titled with the page's origin host.
  198. pushed(text) {
  199. let r = globalThis.__hlAttempt(() => { return JSON.parse(text) })
  200. let p = r.ok && r.value != null && (r.value.title != null || r.value.body != null) ? r.value : { body = text; }
  201. let title = p.title != null ? p.title : globalThis.location.host
  202. let opts = { data = { path = p.url != null ? p.url : '/' }; }
  203. if (p.body != null) { opts.body = p.body }
  204. if (p.tag != null) { opts.tag = p.tag }
  205. if (p.icon != null) { opts.icon = p.icon }
  206. return globalThis.registration.showNotification(title, opts)
  207. }
  208. // A page this app does not carry offline. A DOCUMENT, so the tab shows something and
  209. // no navigation fails inside the browser; 503, so a probe can tell it from a page.
  210. unavailable(path) {
  211. let esc = path.replaceAll('&', '&amp;').replaceAll('<', '&lt;')
  212. let body = '<!doctype html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Offline</title><link rel="stylesheet" href="' + cfg.css + '"></head><body><main data-hl-offline="1"><h1>Unavailable offline</h1><p><code>' + esc + '</code> is not one of the pages this app carries offline.</p><p><a href="/">Back to the start</a></p></main></body></html>'
  213. let R = globalThis.Response
  214. return new R(body, { status = 503 headers = { 'Content-Type' = 'text/html; charset=utf-8' } })
  215. }

Branches

Latest commits

  • 4e018678|||PR deploy.sh: gates use Tracker's ports 8716-8719 and LC_ALL=C; README: 2 backups keptTracker
  • 0b86324aMerge branch 'records-dp73' into mainTracker
  • 9ce5f59b|||PR records: DP73 live 613ae0e; deploy.sh keeps 2 backupsTracker
  • 613ae0ecMerge branch 'bs3' into mainTracker
  • 1383264b|||PR BS3: keep shared synchronous sorting fastTracker
  • 63e5ba1a|||PR BS3: guard boot imports and share resumable sort buffersTracker
  • 310613f1Merge branch 'records-dp72' into mainTracker
  • 6f7b61ba|||PR records: deploy-swap fix live, Kunibert findingsTracker
  • c41587d2Merge branch 'bs2' into mainTracker
  • 0dd538a6|||PR BS2: finish the boot index in slices so a booting instance keeps answeringTracker
  • 019d5cedMerge branch 'records-1110' into mainTracker
  • f88ae8b9|||PR records: day56 toggle live, reviewTracker
  • b6b3bb4dMerge branch 'ap56e' into mainTracker
  • 29a26da9|||PR AP56e: guard hidden show helpers during session syncTracker
  • 7c9ec236|||PR AP56e: re-vendor Hybriel set day56 (source 36ae83a8, bin c1f595a2)Tracker
  • 4b54f6f9Merge branch 'records-audit' into mainTracker
  • cab4a3bc|||PR records: branch audit, PR-onlyTracker
  • 641e1c4cMerge branch 'records-dp71' into mainTracker
  • 85a6e9f5|||PR records: DP71 checked in ChromeTracker
  • f5be5f18records: gitoria PR-only planTracker