gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchplaying-row05c3578c|||PR Keep each playing row bound to the shell song on day76mreplaying-row/plugins/web/offline.hl

38.8 KB

  1. // Offline state and durable emits. The Client handle stays live across navigation;
  2. // seed, page and socket are always read from it, never copied into this feature.
  3. import { registerFeature } from 'hl:web'
  4. client = null
  5. static register = () => { return registerFeature('offline', Offline) }
  6. replayingQ = null // the `q` of the queued entry whose frame is out and not acked (it cannot be taken back)
  7. store = null
  8. memberSep = JSON.parse('"\u0001"') // between a record key and a member name in a per-member record's key
  9. memberEnd = JSON.parse('"\u0002"')
  10. legacyDone = {} // record keys whose pre-per-member combined record was already migrated (this tab)
  11. keptAt = {} // record key + newline + member -> { at, fingerprint }: see keepMembers, #419
  12. channel = null // BroadcastChannel to this app's other tabs: what they put or confirmed in the shared store
  13. jsonCache = new WeakMap() // instance -> Map(member -> immutable JSON snapshot, its text and fingerprint), #419
  14. unacked = {}
  15. replays = {} // 'k<i>' → what ends a replayed entry's wait when its socket closes
  16. live = {} // q → true while a live emit's entry (written before its frame) waits for its ack: the replay leaves it alone
  17. flushing = false
  18. owner = '' // whose the kept copy is (settleWho): the last user logged in
  19. holding = false // an anonymous page over a user's copy: nothing is kept or laid over it
  20. heldBack = false // the server said a queued entry is for another user than the session's
  21. needsResync = false // a locally constructed destination needs full server values on reconnect (#377)
  22. flushAgain = false // an entry was queued while a round ran: the round goes over the queue once more
  23. queueRetryTimer = null // a round that did not fully drain tries again after queueRetryWait
  24. static replayAckTimeout = 20000
  25. static queueRetryWait = 3000
  26. // A DOCUMENT THAT STANDS IN FOR THIS URL (#124): the worker answered an unvisited param page
  27. // with a kept document of the same component, so the seed's parameters are another url's.
  28. // This url's are the truth: they go into the instance, and what they feed is derived again
  29. // here (what only the server can derive stays as that document had it, until a push).
  30. standIn() {
  31. if (client.page == null || client.seed.page == null) { return null }
  32. m = client.router.match(location.pathname)
  33. if (m == null || m.kind != 'component') { return null }
  34. mine = JSON.stringify(m.params)
  35. if (mine == JSON.stringify(client.seed.page.params)) { return null }
  36. for (k of m.params.keys()) { client.page.instance[k] = m.params[k] }
  37. client.seed.page.params = m.params
  38. names = m.params.keys()
  39. if (client.planOf(client.page.key).route == true) {
  40. client.page.instance.route = client.currentRoute()
  41. names.push('route')
  42. }
  43. client.patch(client.page.chain, 'page', client.moved(&client.page, names), [])
  44. return null
  45. }
  46. // A kept route's identity reuses the component marker: an index in offline.pages,
  47. // or the key of a data-free page. true still means an ordinary server page.
  48. localRoute(String path) {
  49. if (holding) { return null }
  50. matched = client.router.match(path)
  51. if (matched == null || matched.kind != 'component') { return null }
  52. marker = matched.route.component
  53. if (hlTypeName(marker) == 'Number') { return client.seed.offline.pages[marker] }
  54. return hlTypeName(marker) == 'String' ? marker : null
  55. }
  56. // No document request and no server construction. The page and its parents are
  57. // ordinary client constructions, with the destination's parameters and kept data.
  58. navigation(String path) {
  59. key = localRoute(path)
  60. if (key == null) { return null }
  61. matched = client.router.match(path)
  62. next = client.seed
  63. next.local = true
  64. next.page = localMount(key, matched.params, [], 'page', path)
  65. levels = []
  66. let at = client.planOf(key).parent
  67. while (at != null && levels.length < 64) {
  68. levels.push(at)
  69. at = client.planOf(at).parent
  70. }
  71. let top = null
  72. let i = 0
  73. while (i < levels.length) {
  74. ch = []
  75. let n = levels.length - i - 1
  76. while (n > 0) { ch.push('^') n = n - 1 }
  77. level = localMount(levels[i], matched.params, ch, 'shell', path)
  78. if (top != null) { level.kids['^'] = top }
  79. top = level
  80. i = i + 1
  81. }
  82. next.shell = top
  83. needsResync = true
  84. return next
  85. }
  86. localMount(String key, Hybrid params, Hybrid chain, String root, String path) {
  87. bp = client.planOf(key)
  88. state = mountState(key, params, chain, root, path)
  89. if (bp.route == true) { state.route = client.currentRoute() }
  90. return { key = key params = params state = state kids = {} }
  91. }
  92. // Exact-address values win for parameter-fed members. Component-wide members
  93. // follow their freshest kept values. An unvisited address has client defaults;
  94. // server-only initializers are pinned to null until reconnect supplies them.
  95. mountState(String key, Hybrid params, Hybrid chain, String root, String path) {
  96. client.planOf(key)
  97. let state = {}
  98. list = client.derivationsOf(key)
  99. for (d of list) { if (d.srv == true) { state[d.name] = null } }
  100. if (store == null || holding) { return state }
  101. base = chain.length == 0 && root == 'page' ? key : (root == 'page' ? kidKey(chain, key) : shellKey(chain, key))
  102. fed = fedBy(key, params)
  103. readState(base, fed, false, &state)
  104. level = root == 'page' && chain.length == 0 || root == 'shell' && isLevel(chain)
  105. readState(base + '|' + path, level ? fed : null, true, &state)
  106. // Match a fresh online page: client members run their initializers. Only
  107. // server-supplied data comes from the offline store, never another page's draft.
  108. for (d of list) {
  109. if (d.srv != true && d.name != 'session' && d.name != 'host' && d.name != 'headers') { delete state[d.name] }
  110. }
  111. return state
  112. }
  113. readState(String key, Hybrid fed, Boolean ofUrl, &state) {
  114. rec = loadRec(key)
  115. if (rec != null) {
  116. for (name of rec.members.keys()) {
  117. if (fed == null || fed.includes(name) == ofUrl) { state[name] = JSON.parse(rec.members[name].v) }
  118. }
  119. }
  120. return null
  121. }
  122. // ---- THE OFFLINE LAYER (COMPONENTS §10) --------------------------------------------
  123. // Live only in an app whose manifest declares `offline = [ … ]`: the seed then says
  124. // which pages it keeps, which emits it may queue, which worker to register, and the
  125. // server's clock at the render. Everything is in ONE IndexedDB database, `hl-offline`:
  126. // state `{ k, members }` under `<component>|<path>`: per member, the freshest value
  127. // this browser was told and the server time it was true at (`{ at, v }`,
  128. // v as JSON) — from the render, from a navigation, from every push
  129. // The shell (and each parent level, and the components composed into them) is kept the
  130. // same way under `@shell|<address>|<component>`, so its keys never meet a page's.
  131. // queue `{ id, event, payload, at, q }`, the id counting up, so the order the entries
  132. // are read in IS the order they were made; `q` is the emit's stable id, the
  133. // same on every try, which the server runs once. A queueable emit on an open socket is
  134. // written here BEFORE its frame goes out and leaves on its ack (sent / ack below)
  135. offlineBoot() {
  136. registerWorker()
  137. store = openStore()
  138. if (store == null) { return null }
  139. if (channel == null && window.BroadcastChannel != null) {
  140. channel = new BroadcastChannel('hlweb-offline:' + location.origin)
  141. channel.onmessage = (Hybrid ev) => { heard(ev.data) }
  142. }
  143. settleWho()
  144. if (keptPage()) {
  145. rehydrate()
  146. remember(client.seed.page.state.keys(), client.seed.offline.at)
  147. rehydrateShell()
  148. rememberShell()
  149. rehydrateKids()
  150. rememberKids()
  151. }
  152. client.syncQueued()
  153. // the network came back: reconnect now, not when the backoff says (the queue then
  154. // goes out at once)
  155. window.addEventListener('online', () => { client.reconnectNow() })
  156. return null
  157. }
  158. // WHOSE THE KEPT COPY IS (ticket #125). The seed says who the session is (an opaque value,
  159. // '' for nobody); the copy remembers its OWNER under `@who`: the last user who was logged
  160. // in. A session that expired, or a fresh anonymous one, owns nothing and changes nothing:
  161. // the owner's queue is HELD (not replayed, not dropped) and nothing is laid over or kept
  162. // for the anonymous page. The owner logging in again replays it; ANOTHER user logging in
  163. // forgets the owner's copy. The first user to log in adopts a copy that had no owner.
  164. settleWho() {
  165. rec = done(objects('state', 'readonly').get('@who'))
  166. owner = rec != null ? rec.who : ''
  167. w = client.seed.offline.who
  168. holding = w == '' && owner != ''
  169. if (w == '' || owner == w) { return null }
  170. if (owner == '') {
  171. owner = w
  172. done(objects('state', 'readwrite').put({ k = '@who'; who = w; }))
  173. return null
  174. }
  175. return forget(w)
  176. }
  177. // A FACE CHANGED WHOSE SESSION THIS IS (the ack says so): a log-out forgets the copy, a login
  178. // is settled like a page that arrived under that user
  179. whoChanged(String w) {
  180. client.dropKept()
  181. if (w == client.seed.offline.who) { return null }
  182. client.seed.offline.who = w
  183. if (w == '') { return forget('') }
  184. return settleWho()
  185. }
  186. // an explicit log-out: the owner's state, queue and documents all go
  187. forgetOffline() {
  188. client.dropKept()
  189. return forget('')
  190. }
  191. // the state, the queue and the worker's documents go; the copy is now `to`'s. The worker
  192. // keeps the page that stands again, fetched as this session sees it.
  193. forget(String to) {
  194. if (store == null || client.seed == null || client.seed.offline == null) { return null }
  195. done(objects('state', 'readwrite').clear())
  196. done(objects('queue', 'readwrite').clear())
  197. done(objects('state', 'readwrite').put({ k = '@who'; who = to; }))
  198. keptAt = {}
  199. tell({ t = 'clear'; })
  200. owner = to
  201. holding = client.seed.offline.who == '' && to != ''
  202. sw = navigator.serviceWorker
  203. if (sw != null && sw.controller != null) { sw.controller.postMessage({ t = 'forget'; path = location.pathname + location.search; }) }
  204. client.syncQueued()
  205. return null
  206. }
  207. // is the mounted page one the app keeps?
  208. keptPage() {
  209. return client.page != null && client.seed.offline != null && !holding && client.seed.offline.pages.includes(client.page.key)
  210. }
  211. // THE WORKER, registered once: a page it already controls has it, and the browser
  212. // itself checks the entry script for a new build at every navigation
  213. registerWorker() {
  214. sw = navigator.serviceWorker
  215. if (sw == null || sw.controller != null) { return null }
  216. r = window.__hlAttempt(() => { return sw.register(client.seed.offline.worker, { scope = '/' type = 'module' }) })
  217. if (!r.ok) { console.warn('framework: the offline worker could not be registered — ' + r.error) }
  218. return null
  219. }
  220. openStore() {
  221. if (window.indexedDB == null) { return null }
  222. // A BROWSER'S OPEN CAN STAY PENDING (a loaded Chrome: the request neither succeeds nor fails, W88/W99, Atlas G2):
  223. // boot awaits this store before it connects, so the page never finished hydrating. The open is given 3 s; after
  224. // that the page runs without its offline copy (store null, as when IndexedDB is missing) and a late success is closed.
  225. return new Promise((Function res, Function rej) => {
  226. let gaveUp = false
  227. req = indexedDB.open('hl-offline', 1)
  228. timer = setTimeout(() => { gaveUp = true res(null) }, 3000)
  229. req.onupgradeneeded = () => {
  230. db = req.result
  231. db.createObjectStore('state', { keyPath = 'k' })
  232. db.createObjectStore('queue', { keyPath = 'id' autoIncrement = true })
  233. }
  234. req.onsuccess = () => {
  235. if (gaveUp) { req.result.close() return null }
  236. clearTimeout(timer)
  237. res(req.result)
  238. }
  239. req.onerror = () => { clearTimeout(timer) res(null) }
  240. })
  241. }
  242. // one object store, in its own transaction
  243. objects(String name, String mode) {
  244. return store.transaction(name, mode).objectStore(name)
  245. }
  246. // an IndexedDB request's result; null when it failed
  247. done(Hybrid req) {
  248. return new Promise((Function res, Function rej) => {
  249. req.onsuccess = () => { res(req.result) }
  250. req.onerror = () => { res(null) }
  251. })
  252. }
  253. // WHERE THIS PAGE'S STATE IS KEPT (ticket #123). A member that no route parameter feeds is
  254. // the component's: the same list at `/` and at `/notes/:id`, so it is kept ONCE, under the
  255. // component, and every url of it reads the freshest. A member a route parameter feeds — the
  256. // parameter itself, and every derivation that reads one, transitively — is that url's.
  257. stateKey() {
  258. return client.page.key + '|' + location.pathname + location.search
  259. }
  260. paramFed() {
  261. return fedBy(client.page.key, client.seed.page != null ? client.seed.page.params : null)
  262. }
  263. // the members of component `key` that its route parameters feed (the parameters, and everything derived from them)
  264. fedBy(String key, Hybrid params) {
  265. fed = ['route']
  266. if (params != null) {
  267. for (k of params.keys()) { fed.push(k) }
  268. }
  269. list = client.derivationsOf(key)
  270. let again = true
  271. while (again) {
  272. again = false
  273. for (d of list) {
  274. if (!fed.includes(d.name) && client.feedsFrom(d, fed)) {
  275. fed.push(d.name)
  276. again = true
  277. }
  278. }
  279. // a feed a declared handler fills from what it reads of this page's route-fed members (#404)
  280. for (m of client.handlerFed(key)) {
  281. if (!fed.includes(m)) {
  282. for (r of client.handlerFeedsOf(key, m)) {
  283. if (fed.includes(r)) { fed.push(m) again = true break }
  284. }
  285. }
  286. }
  287. }
  288. return fed
  289. }
  290. // KEEP what the server said the named members of the page are, as of `at` (its
  291. // clock), the url's under the url and the others under the component.
  292. remember(Hybrid names, Number at) {
  293. if (store == null || !keptPage()) { return null }
  294. fed = paramFed()
  295. byUrl = []
  296. byComponent = []
  297. for (n of names) {
  298. if (fed.includes(n)) { byUrl.push(n) } else { byComponent.push(n) }
  299. }
  300. keepMembers(stateKey(), byUrl, at)
  301. keepMembers(client.page.key, byComponent, at)
  302. return null
  303. }
  304. // ONLY THE MEMBERS WHOSE VALUE CHANGED ARE WRITTEN, AT ONCE (#419; write-through stays: no debounce,
  305. // no batching). A member whose value is the one this tab knows the store holds is neither
  306. // stringified (memberJson) nor put, and its record is not even read.
  307. //
  308. // WHY AN EQUAL VALUE MAY LEAVE ITS STORED `at` OLD. What is stored is the member's value as this tab
  309. // LIVES it, tagged with the server time of the answer that carried it; `at` only decides which of two
  310. // writers of DIFFERENT values wins. A value equal to the stored one is already the stored truth, so
  311. // the old `at` costs nothing at rehydrate (a document newer than that `at` was rendered from the same
  312. // value, or a later change would have been written). What the old `at` WOULD cost is the guard: a late
  313. // OLDER answer (a navigation answer applied after a push; another tab's lagging write) must not win
  314. // against a value that was confirmed newer. That guard is `keptAt`: per record key and member, the
  315. // newest `at` this tab wrote OR confirmed and length plus two 32-bit hashes (null = unknown).
  316. // A write older than that is refused, exactly as the stored `at` refused it before. Other tabs
  317. // share the store, so each put and each confirmation is told to them over a BroadcastChannel
  318. // (messages from one tab arrive in order): a peer's put makes the text unknown (the next apply
  319. // reads the record), a peer's confirmation raises the guard. The guard lives as long as the tab; a
  320. // reload starts it empty and the first apply reads the stored `at` as before. The meaning of `at`
  321. // is unchanged; the layout is D27's: one record per member (memberKey), so a changed member is the
  322. // only thing written.
  323. keepMembers(String k, Hybrid names, Number at, Hybrid chain = null, String root = 'shell') {
  324. if (names.length == 0) { return null }
  325. vals = {}
  326. fingerprints = {}
  327. need = [] // the names this tab does not know the store to hold already: only these are read and written
  328. let slow = false
  329. for (n of names) {
  330. if (n != '__hlQueued' && n != '__hlQueue' && n != '__hlOnline' && n != '__hlReach' && n != '$notifyPermission') {
  331. snapshot = chain == null ? memberJson(client.page.instance, n) : client.shellValue(chain, n, root)
  332. if (snapshot != null && snapshot.text != null) {
  333. v = snapshot.text
  334. vals[n] = v
  335. fp = snapshot.fingerprint
  336. fingerprints[n] = fp
  337. e = keptAt[k + '\n' + n]
  338. if (e == null || e.fingerprint == null || e.fingerprint != fp) { slow = true need.push(n) }
  339. else if (at > e.at) { keptAt[k + '\n' + n] = { at = at; fingerprint = fp; } }
  340. }
  341. }
  342. }
  343. if (!slow) {
  344. tell({ t = 'ok'; k = k; names = window.Array.from(vals.keys()); at = at; })
  345. return null
  346. }
  347. migrateLegacy(k)
  348. recKey = k
  349. os = objects('state', 'readwrite')
  350. written = []
  351. confirmed = []
  352. for (n of need) {
  353. v = vals[n]
  354. fp = fingerprints[n]
  355. e = keptAt[k + '\n' + n]
  356. floor = e == null ? 0 : e.at
  357. mk = memberKey(k, n)
  358. s = done(os.get(mk))
  359. if ((s != null && s.at > at) || floor > at) {
  360. // an answer older than one already kept or confirmed: the newer stays
  361. keptAt[k + '\n' + n] = { at = (s != null && s.at > floor) ? s.at : floor; fingerprint = null; }
  362. } else if (s != null && s.v == v) {
  363. keptAt[k + '\n' + n] = { at = at; fingerprint = fp; }
  364. confirmed.push(n)
  365. } else {
  366. done(os.put({ k = mk; rec = recKey; n = n; at = at; v = v; }))
  367. keptAt[k + '\n' + n] = { at = at; fingerprint = fp; }
  368. written.push(n)
  369. }
  370. }
  371. if (written.length > 0) { tell({ t = 'put'; k = k; names = written; at = at; }) }
  372. for (n of vals.keys()) { if (!need.includes(n)) { confirmed.push(n) } }
  373. if (confirmed.length > 0) { tell({ t = 'ok'; k = k; names = confirmed; at = at; }) }
  374. return null
  375. }
  376. // The guard keeps every confirmation time, including equal values not put to IDB.
  377. // Retain only a digest of the JSON: visited addresses must not pin their full texts.
  378. fingerprint(String text) {
  379. return window.__hlP.FP(text)
  380. }
  381. // ONE RECORD PER MEMBER (D27: state per component+path+key): `<record key> \u0001 <member>` holds
  382. // { k, rec, n, at, v }. Only a changed member's record is written, at once. A reader gets the members of
  383. // one record key as the `{ members = { name = { at, v } } }` shape the combined record had.
  384. memberKey(String k, String n) {
  385. return k + memberSep + n
  386. }
  387. loadRec(String k) {
  388. migrateLegacy(k)
  389. rows = done(objects('state', 'readonly').getAll(window.IDBKeyRange.bound(k + memberSep, k + memberEnd, false, true)))
  390. if (rows == null || rows.length == 0) { return null }
  391. rec = { k = k; members = {}; }
  392. for (r of rows) { rec.members[r.n] = { at = r.at; v = r.v; } }
  393. return rec
  394. }
  395. // An install from before the per-member layout holds ONE record under the bare key, all members in
  396. // it. The first touch of that key (this tab, once) copies each member that has no per-member record,
  397. // or an older one, into its own, then drops the combined record: nothing is lost and every reader
  398. // afterwards sees one layout. Read and written in one transaction; another tab doing the same
  399. // concurrently writes the same values (a member is only written over an older or missing one).
  400. migrateLegacy(String k) {
  401. if (legacyDone[k] == true) { return null }
  402. legacyDone[k] = true
  403. old = done(objects('state', 'readonly').get(k))
  404. if (old == null || old.members == null) { return null }
  405. recKey = k
  406. os = objects('state', 'readwrite')
  407. fresh = done(os.get(k))
  408. if (fresh == null) { return null }
  409. for (n of fresh.members.keys()) {
  410. mk = memberKey(k, n)
  411. cur = done(os.get(mk))
  412. if (cur == null || cur.at < fresh.members[n].at) { done(os.put({ k = mk; rec = recKey; n = n; at = fresh.members[n].at; v = fresh.members[n].v; })) }
  413. }
  414. done(os.delete(k))
  415. return null
  416. }
  417. tell(Hybrid m) {
  418. if (channel != null) { channel.postMessage(m) }
  419. return null
  420. }
  421. // what another tab of this app told about the shared store
  422. heard(Hybrid m) {
  423. if (m.t == 'clear') { keptAt = {} return null }
  424. for (n of m.names) {
  425. e = keptAt[m.k + '\n' + n]
  426. top = (e != null && e.at > m.at) ? e.at : m.at
  427. keptAt[m.k + '\n' + n] = { at = top; fingerprint = (m.t == 'ok' && e != null) ? e.fingerprint : null; }
  428. }
  429. return null
  430. }
  431. // An independent JSON snapshot and cached fingerprint, never a handle to the live member: nested writes must
  432. // invalidate it too. hlSame compares without making an argument copy or JSON text;
  433. // JSON's named keys are sorted, so an equal value has the same serialized text.
  434. // Weak instance keys let navigation release snapshots of unmounted components.
  435. memberJson(Hybrid inst, String name) {
  436. let cache = jsonCache.get(inst)
  437. if (cache == null) { cache = new Map() jsonCache.set(inst, cache) }
  438. cached = cache.get(name)
  439. if (cached != null && hlSame(&inst[name], &cached.value)) { return { text = cached.text; fingerprint = cached.fingerprint; } }
  440. text = JSON.stringify(&inst[name])
  441. fp = text == null ? null : fingerprint(text)
  442. if (text != null && snapshotable(&inst[name])) {
  443. // A private value copy keeps immutable strings as-is, unlike reparsing JSON.
  444. // Only this snapshot is shared: app member values keep their copy rules.
  445. value = inst[name]
  446. snapshot = { text = text fingerprint = fp value = hlShared(&value) }
  447. cache.set(name, hlShared(&snapshot))
  448. } else { cache.delete(name) }
  449. return { text = text; fingerprint = fp; }
  450. }
  451. // Class/host handles can change behind a value copy or serialize through a hook.
  452. // They always take the original stringify path. Pure hybrid data copies independently.
  453. snapshotable(&value, Number depth = 0) {
  454. kind = hlTypeName(&value)
  455. if (kind == 'Null' || kind == 'Undefined' || kind == 'String' || kind == 'Number' || kind == 'Boolean') { return true }
  456. if (kind != 'Hybrid' || depth >= 64 || window.Reflect.get(&value, 'toJSON') != null) { return false }
  457. if (Array.isArray(&value)) {
  458. for (let i = 0; i < value.length; i = i + 1) {
  459. if (!snapshotable(&value[i], depth + 1)) { return false }
  460. }
  461. }
  462. for (k of value.keys()) { if (!snapshotable(&value[k], depth + 1)) { return false } }
  463. return true
  464. }
  465. // AT BOOT, the kept values that are NEWER than this document are laid over it: a
  466. // document the worker served from its cache is as old as the visit that cached it,
  467. // and what a later push said is the fresher truth. A document the network just
  468. // rendered is newer than everything kept, and nothing is laid over it.
  469. rehydrate() {
  470. fed = paramFed()
  471. names = laidOver(loadRec(stateKey()), fed, true)
  472. for (n of laidOver(loadRec(client.page.key), fed, false)) { names.push(n) }
  473. client.patch(client.page.chain, 'page', names, [])
  474. return null
  475. }
  476. // the members of one kept record that are the url's (`fed`) or not, and newer than the document
  477. // (`chain`: null for the page, else the address of the shell mount they are laid over)
  478. laidOver(Hybrid rec, Hybrid fed, Boolean ofUrl, Hybrid chain = null, String root = 'shell') {
  479. names = []
  480. if (rec == null) { return names }
  481. for (n of rec.members.keys()) {
  482. e = rec.members[n]
  483. if (e.at > client.seed.offline.at && fed.includes(n) == ofUrl) {
  484. if (chain == null) { client.page.instance[n] = JSON.parse(e.v) } else { client.shellLay(chain, n, e.v, root) }
  485. names.push(n)
  486. }
  487. }
  488. return names
  489. }
  490. // THE SHELL, ITS PARENT LEVELS AND THE COMPONENTS COMPOSED INTO THEM (#341) are kept by the
  491. // page's rules: per member, with the server's time, laid over a cached document at boot only
  492. // when newer. They stand at an address (`chain`: [] the shell, ['^'] the next level, …), under
  493. // `@shell|<address>|<component>` so no key is a page's. A level's members that a route parameter
  494. // feeds are that url's (as the page's are). Composed mounts keep exact-url records,
  495. // with a component-wide fallback only for members independent of route and host inputs (#447).
  496. shellKey(Hybrid chain, String key) {
  497. return '@shell|' + chain.join('/') + '|' + key
  498. }
  499. isLevel(Hybrid chain) {
  500. for (c of chain) { if (c != '^') { return false } }
  501. return true
  502. }
  503. shellFed(Hybrid chain, String key) {
  504. if (!isLevel(chain)) { return fedBy(key, client.mountInputs(chain, 'shell')) }
  505. return fedBy(key, client.routeParams()[key])
  506. }
  507. rehydrateShell() {
  508. for (m of client.shellMounts()) {
  509. fed = shellFed(m.chain, m.key)
  510. k = shellKey(m.chain, m.key)
  511. let names = []
  512. if (!isLevel(m.chain)) {
  513. names = laidOver(loadRec(k), fed, false, m.chain)
  514. for (n of laidOver(loadRec(k + '|' + location.pathname + location.search), [], false, m.chain)) { names.push(n) }
  515. } else {
  516. names = laidOver(loadRec(k + '|' + location.pathname + location.search), fed, true, m.chain)
  517. for (n of laidOver(loadRec(k), fed, false, m.chain)) { names.push(n) }
  518. }
  519. client.patch(m.chain, 'shell', names, [])
  520. }
  521. return null
  522. }
  523. // what the render gave the shell mounts, kept as of the render's time
  524. rememberShell() {
  525. if (store == null || !keptPage()) { return null }
  526. for (m of client.shellMounts()) { rememberMount(m.chain, m.key, m.names, client.seed.offline.at) }
  527. return null
  528. }
  529. // THE COMPONENTS COMPOSED INTO THE PAGE (#343), at any depth, are kept by the same rules, with the
  530. // same walk (client.pageMounts is collectMounts from the page root): exact-url records under
  531. // `@page|<address>|<component>`, so no key is a page's or a shell's. The page root's own members
  532. // are the page's (remember above).
  533. kidKey(Hybrid chain, String key) {
  534. return '@page|' + chain.join('/') + '|' + key
  535. }
  536. rehydrateKids() {
  537. for (m of client.pageMounts()) {
  538. fed = fedBy(m.key, client.mountInputs(m.chain, 'page'))
  539. k = kidKey(m.chain, m.key)
  540. let names = laidOver(loadRec(k), fed, false, m.chain, 'page')
  541. for (n of laidOver(loadRec(k + '|' + location.pathname + location.search), [], false, m.chain, 'page')) { names.push(n) }
  542. client.patch(m.chain, 'page', names, [])
  543. }
  544. return null
  545. }
  546. rememberKids() {
  547. if (store == null || !keptPage()) { return null }
  548. for (m of client.pageMounts()) { rememberMount(m.chain, m.key, m.names, client.seed.offline.at, 'page') }
  549. return null
  550. }
  551. // KEEP the named members of one mount of the shell (or, with root 'page', of the page's composed components), as of `at`
  552. rememberMount(Hybrid chain, String key, Hybrid names, Number at, String root = 'shell') {
  553. if (store == null || !keptPage()) { return null }
  554. fed = root == 'page' ? fedBy(key, client.mountInputs(chain, root)) : shellFed(chain, key)
  555. k = root == 'page' ? kidKey(chain, key) : shellKey(chain, key)
  556. url = k + '|' + location.pathname + location.search
  557. if (fed == null) {
  558. keepMembers(url, names, at, chain, root)
  559. return null
  560. }
  561. byUrl = []
  562. byComponent = []
  563. for (n of names) {
  564. if (fed.includes(n)) { byUrl.push(n) } else { byComponent.push(n) }
  565. }
  566. keepMembers(url, isLevel(chain) && root == 'shell' ? byUrl : names, at, chain, root)
  567. keepMembers(k, byComponent, at, chain, root)
  568. return null
  569. }
  570. // AN EMIT THAT DID NOT REACH THE SERVER. A page the app keeps queues it; any other
  571. // says so. It answers null either way: nothing was answered.
  572. undelivered(String event, Hybrid payload, String q) {
  573. if (store != null && client.seed.offline.queue.includes(event)) {
  574. enqueue(event, payload, q)
  575. return null
  576. }
  577. // (a navigation's own `page` emit is not reported: it falls back to loading the
  578. // document, which the worker answers)
  579. if (event != 'page') { console.warn('framework: ' + event + ' did not reach the server, and it is not an emit a page this app keeps offline may queue') }
  580. return null
  581. }
  582. // A FILE WAITS WITH ITS EMIT: IndexedDB keeps a File as it is, so the entry's `files`
  583. // holds them and each one's place in the payload names it, `{ __hlFile = n, name, type,
  584. // size }` (what a page shows of it in `__hlQueue`)
  585. enqueue(String event, Hybrid payload, String q) {
  586. done(objects('queue', 'readwrite').add(entryOf(event, payload, q)))
  587. client.syncQueued()
  588. // (an entry added while a round runs is taken by that round's next pass)
  589. if (flushing) { flushAgain = true }
  590. // A LIVE EMIT CAN LAND HERE WITH ITS SOCKET STILL OPEN (crossing() above, when only
  591. // its UPLOAD dropped): nothing closed, so there is no "next open" to replay it on.
  592. // flush() is asked for right away — a no-op with no live socket, same as always.
  593. flush()
  594. return null
  595. }
  596. // the queue row of an emit, its files beside it
  597. entryOf(String event, Hybrid payload, String q) {
  598. files = []
  599. kept = []
  600. for (a of payload) {
  601. if (client.isFile(a)) {
  602. kept.push(fileMark(a, files.length))
  603. files.push(a)
  604. } else if (client.isFileList(a)) {
  605. marks = []
  606. let j = 0
  607. while (j < a.length) {
  608. provider = client.uploadsReady()
  609. f = provider != null ? provider.fileAt(a, j) : (hlTypeName(a) == 'Hybrid' ? a[j] : a.item(j))
  610. marks.push(fileMark(f, files.length))
  611. files.push(f)
  612. j = j + 1
  613. }
  614. kept.push(marks)
  615. } else {
  616. kept.push(a)
  617. }
  618. }
  619. return { event = event; payload = JSON.stringify(kept); files = files; at = Date.now(); q = q; who = client.seed.offline.who; }
  620. }
  621. // WRITE BEFORE SEND (#339). A queueable emit about to go out on an open socket is in the queue
  622. // first, one transaction, committed before the frame is sent: a page killed while its socket is
  623. // open and silent (a stalled connection) still has the emit, and the next socket replays it.
  624. // It leaves the queue on its ack (ack below). The replay of it and the ack of it can meet (the
  625. // ack arrived, the page was killed before the delete): the entry then goes out again under the
  626. // same `q`, which the server has kept, and it answers the repeat without running it again.
  627. // While the emit is live the replay and the queue's readers leave it alone (`live`).
  628. // Answers 'sent' (the frame may go out), or 'queued' (the socket was lost while the entry was
  629. // written: it waits for the next one and nothing is sent now).
  630. sent(String k, String event, Hybrid payload, String q) {
  631. if (store == null) {
  632. unacked[k] = { event = event; payload = payload; q = q; id = null; }
  633. return 'sent'
  634. }
  635. live[q] = true
  636. id = commitRow(entryOf(event, payload, q))
  637. if (id == null) {
  638. // (the write failed: the emit is kept in memory as before, and queued if the socket is lost)
  639. live[q] = null
  640. if (client.socket == null || client.socket.readyState != 1) {
  641. enqueue(event, payload, q)
  642. return 'queued'
  643. }
  644. unacked[k] = { event = event; payload = payload; q = q; id = null; }
  645. return 'sent'
  646. }
  647. if (client.socket == null || client.socket.readyState != 1) {
  648. live[q] = null
  649. client.syncQueued()
  650. return 'queued'
  651. }
  652. unacked[k] = { event = event; payload = payload; q = q; id = id; }
  653. return 'sent'
  654. }
  655. // one row added in its own transaction; its id once the transaction has committed, null when it failed
  656. commitRow(Hybrid rec) {
  657. return new Promise((Function res, Function rej) => {
  658. let tx = null
  659. let req = null
  660. let made = window.__hlAttempt(() => {
  661. tx = store.transaction('queue', 'readwrite')
  662. req = tx.objectStore('queue').add(rec)
  663. return 1
  664. })
  665. if (!made.ok) { res(null) return null }
  666. tx.oncomplete = () => { res(req.result) }
  667. tx.onerror = () => { res(null) }
  668. tx.onabort = () => { res(null) }
  669. })
  670. }
  671. // whether entries made for this user wait in the queue, or a replay is under way
  672. queuedAhead() {
  673. if (flushing) { return true }
  674. let rows = done(objects('queue', 'readonly').getAll())
  675. if (rows == null) { return false }
  676. for (r of rows) { if (r.who == client.seed.offline.who && live[r.q] != true) { return true } }
  677. return false
  678. }
  679. fileMark(Hybrid f, Number n) {
  680. return { __hlFile = n name = f.name != null ? f.name : '' type = f.type size = f.size }
  681. }
  682. isFileMark(Hybrid | String | Number | Boolean | Bytes | Function a) {
  683. return hlTypeName(a) == 'Hybrid' && a.__hlFile != null
  684. }
  685. // A REPLAY GIVES A DROPPED UPLOAD MORE THAN ONE TRY (mission 2026-09-26): the socket
  686. // having just reopened says the network is back, so a stall here reads as congestion,
  687. // not as "offline" — unlike a live emit's `uploadFile` (uploadAll above), which still
  688. // gives up on the first drop, so an app that is genuinely offline queues at once
  689. // instead of waiting out a retry budget it does not need. `uploadFile` resumes from
  690. // what the server already has (`begun.have`), so asking it again is exactly a retry,
  691. // not a restart.
  692. uploadFileReplay(String event, Number index, Hybrid f, String q) {
  693. provider = client.uploadsReady()
  694. if (provider == null) { return { error = 'files could not start because the upload module could not be loaded' dropped = true } }
  695. let up = provider.uploadFile(event, index, f, q)
  696. let misses = 0
  697. while (up.dropped == true) {
  698. misses = misses + 1
  699. if (misses > provider.uploadRetries) { return up }
  700. provider.uploadWait(misses)
  701. up = provider.uploadFile(event, index, f, q)
  702. }
  703. return up
  704. }
  705. // a queued entry's files, sent as the emit's own were (`uploadFile`, under its `q` and
  706. // their places): the payload with every mark replaced by `{ __hlUpload = id }`
  707. uploadKept(String event, Hybrid payload, Hybrid files, String q) {
  708. out = []
  709. for (a of payload) {
  710. if (isFileMark(a)) {
  711. up = uploadFileReplay(event, a.__hlFile, files[a.__hlFile], q)
  712. if (up.error != null) { return up }
  713. out.push({ __hlUpload = up.id })
  714. } else if (hlTypeName(a) == 'Hybrid' && a.length != null && a.length > 0 && isFileMark(a[0])) {
  715. ids = []
  716. for (m of a) {
  717. up = uploadFileReplay(event, m.__hlFile, files[m.__hlFile], q)
  718. if (up.error != null) { return up }
  719. ids.push({ __hlUpload = up.id })
  720. }
  721. out.push(ids)
  722. } else {
  723. out.push(a)
  724. }
  725. }
  726. return { payload = out }
  727. }
  728. // THE SOCKET CLOSED: every queueable emit it had not acked is queued, and a replay it
  729. // was carrying stops (its entry is still in the queue — it leaves only on its ack)
  730. unanswered() {
  731. for (k of unacked.keys()) {
  732. u = unacked[k]
  733. if (u != null) {
  734. unacked[k] = null
  735. client.inflight[k] = null
  736. res = client.pending[k]
  737. client.pending[k] = null
  738. // (a live emit's entry is in the queue already: it is only let go of, and replayed on the next socket)
  739. if (u.id != null) { live[u.q] = null client.syncQueued() } else { enqueue(u.event, u.payload, u.q) }
  740. if (res != null) { res(null) }
  741. }
  742. }
  743. for (k of replays.keys()) {
  744. stop = replays[k]
  745. if (stop != null) {
  746. replays[k] = null
  747. client.pending[k] = null
  748. stop()
  749. }
  750. }
  751. return null
  752. }
  753. // THE REPLAY, when a socket opens: every queued entry, oldest first, as an emit frame on
  754. // that socket; the next goes out when this one is acked, and an entry leaves the queue
  755. // only on its ack. A socket that closes midway stops it, and the next open resumes it.
  756. // A ROUND THAT DID NOT FINISH SCHEDULES ITS OWN NEXT TRY (mission 2026-09-26): a socket
  757. // that stays open the whole time never fires the "next open" above, so a step stuck
  758. // inside `replay()` — an upload, or the ack, whichever gave up — must not depend on one.
  759. // `replay()` itself is bounded (uploadCall's stall guard, and the ack wait's own below),
  760. // so `flushing` always clears; this is what makes a jam at any ONE step a delay, not a
  761. // stop.
  762. flush() {
  763. if (flushing || store == null) { return null }
  764. flushing = true
  765. heldBack = false
  766. let drained = true
  767. let again = true
  768. while (again) {
  769. again = false
  770. flushAgain = false
  771. let rows = done(objects('queue', 'readonly').getAll())
  772. if (rows == null) { rows = [] }
  773. for (r of rows) {
  774. replayingQ = null
  775. // NEVER UNDER ANOTHER USER (#125): an entry waits for the user it was made for; one
  776. // from before users were kept (no user) cannot say whose it is, and is dropped unsent
  777. if (done(objects('queue', 'readonly').get(r.id)) == null) {
  778. // (taken back while this round ran)
  779. } else if (r.who == null) {
  780. done(objects('queue', 'readwrite').delete(r.id))
  781. client.syncQueued()
  782. } else if (r.who != client.seed.offline.who) {
  783. } else if (live[r.q] == true) {
  784. // (a live emit waiting for its ack: its frame is out already)
  785. } else if (flushing && replay(r)) {
  786. done(objects('queue', 'readwrite').delete(r.id))
  787. client.syncQueued()
  788. } else {
  789. flushing = false
  790. drained = false
  791. }
  792. }
  793. if (drained && flushAgain && flushing) { again = true }
  794. }
  795. flushing = false
  796. replayingQ = null
  797. // Another tab may have replayed and removed the shared rows before this round
  798. // read them. Refresh even when this round had no row of its own to delete.
  799. client.syncQueued()
  800. if (!drained && !heldBack) {
  801. if (queueRetryTimer != null) { clearTimeout(queueRetryTimer) }
  802. queueRetryTimer = setTimeout(() => { queueRetryTimer = null flush() }, queueRetryWait)
  803. }
  804. return null
  805. }
  806. // one entry on the socket; true when it was acked. ITS FILES GO UP FIRST, under the
  807. // entry's `q`: an upload a dropped connection cut short goes on where it stopped (and the
  808. // entry stays queued), one the server refuses drops the entry with the error, and one
  809. // whose emit the server already handled is not sent again. THE ACK ITSELF IS BOUNDED
  810. // too (`replayAckTimeout`): a socket the heartbeat has not yet caught, or never will for
  811. // this one, must not hold this promise — and `flush()` — open forever.
  812. replay(Hybrid r) {
  813. let s = client.socket
  814. if (s == null || s.readyState != 1) { return false }
  815. let payload = JSON.parse(r.payload)
  816. if (r.files != null && r.files.length > 0) {
  817. let sent = uploadKept(r.event, payload, r.files, r.q)
  818. if (sent.dropped == true) { return false }
  819. if (sent.error != null) {
  820. console.error("framework: the queued emit '" + r.event + "' is dropped: the upload of " + sent.error)
  821. return true
  822. }
  823. payload = sent.payload
  824. s = client.socket
  825. if (s == null || s.readyState != 1) { return false }
  826. }
  827. client.nextId = client.nextId + 1
  828. i = client.nextId
  829. f = { t = 'emit'; i = i; event = r.event; payload = payload; }
  830. if (r.q != null) { f.q = r.q replayingQ = r.q }
  831. if (r.who != null) { f.w = r.who }
  832. text = JSON.stringify(f)
  833. k = 'k' + i
  834. return new Promise((Function res, Function rej) => {
  835. let settled = false
  836. giveUp = setTimeout(() => {
  837. if (settled) { return null }
  838. settled = true
  839. client.pending[k] = null
  840. replays[k] = null
  841. res(false)
  842. return null
  843. }, replayAckTimeout)
  844. client.pending[k] = (Hybrid | String | Number | Boolean | Bytes | Function answer) => {
  845. if (settled) { return null }
  846. settled = true
  847. clearTimeout(giveUp)
  848. res(!heldBack)
  849. return null
  850. }
  851. replays[k] = () => {
  852. if (settled) { return null }
  853. settled = true
  854. clearTimeout(giveUp)
  855. res(false)
  856. return null
  857. }
  858. s.send(text)
  859. })
  860. }
  861. ready() { return store != null }
  862. queueable(String event) { return client.seed.offline.queue.includes(event) }
  863. ack(String k, Boolean held = false) {
  864. if (held) { heldBack = true }
  865. u = unacked[k]
  866. unacked[k] = null
  867. replays[k] = null
  868. // A LIVE EMIT'S ENTRY LEAVES ON ITS ACK (not waited for: the delete is asked for, and `live` holds
  869. // the replay off until it is done). An ack that says the entry is for another user's session keeps it.
  870. if (u != null && u.id != null) {
  871. if (held) { live[u.q] = null } else { dropRow(u.id, u.q) }
  872. }
  873. return null
  874. }
  875. dropRow(Number id, String q) {
  876. let tx = null
  877. let r = window.__hlAttempt(() => {
  878. tx = store.transaction('queue', 'readwrite')
  879. tx.objectStore('queue').delete(id)
  880. return 1
  881. })
  882. if (!r.ok) { live[q] = null return null }
  883. tx.oncomplete = () => { live[q] = null }
  884. tx.onerror = () => { live[q] = null }
  885. tx.onabort = () => { live[q] = null }
  886. return null
  887. }
  888. ownerOf(String w) {
  889. if (store != null && w != null) { whoChanged(w) }
  890. return null
  891. }
  892. arrived(String path) {
  893. // Local defaults are never stamped as a new server observation.
  894. if (client.seed.local == true) { return null }
  895. if (store != null) { settleWho() }
  896. if (client.page != null && client.seed.offline.pages.includes(client.page.key)) {
  897. remember(client.seed.page.state.keys(), client.seed.offline.at)
  898. rememberShell()
  899. rememberKids()
  900. sw = navigator.serviceWorker
  901. if (sw != null && sw.controller != null) { sw.controller.postMessage({ t = 'keep'; path = path; }) }
  902. }
  903. return null
  904. }
  905. rows() {
  906. if (store == null) { return [] }
  907. records = done(objects('queue', 'readonly').getAll())
  908. if (records == null) { return [] }
  909. out = []
  910. for (r of records) { if (live[r.q] != true) { out.push(r) } }
  911. return out
  912. }
  913. cancel(String q) {
  914. if (store == null || q == replayingQ) { return false }
  915. for (r of rows()) {
  916. if (r.q == q) {
  917. done(objects('queue', 'readwrite').delete(r.id))
  918. client.syncQueued()
  919. return true
  920. }
  921. }
  922. return false
  923. }

Branches

Latest commits

  • 05c3578c|||PR Keep each playing row bound to the shell song on day76mre
  • eaa7e6d6Vendor Hybriel day76 for live parent member readsmre
  • 0923398bMerge branch 'records-1124d' into mainJukebox
  • 78f0cc86|||PR records 2026-11-24: inbox-thread rule, "Not playing" confirmed and closedmre
  • c1b153c4Merge branch 'records-1124c' into mainJukebox
  • d7b5e780|||PR Records 2026-11-24 (2): live day72, PR #19 merge, #10 newsmre
  • 43b564dbMerge branch 'records-1124b' into mainJukebox
  • fa86b08c|||PR Records 2026-11-24: LOG, STATUS, missions 020-023mre
  • 0a2ae3daMerge remote-tracking branch 'origin/records-1123' into records-1124mre
  • 9a48cfcaMerge branch 'vendor-theme' into mainJukebox
  • 170d3735Merge branch 'code-order-2' into mainJukebox
  • 3f1918a7|||PR Re-sync layouts theme 4099e64 with Segoe UI firstmre
  • 2e7f6a43Vendor virtual-list 489afcf from components.hybrielmre
  • 0ba85799Merge branch 'reset-classes' into mainJukebox
  • 502eeed5jukebox#20: vendor virtual-list initial resetKey baseline fixmre
  • 6d5ce287|||PR jukebox#9 Centralize songs table reads and writes in db.hlmre
  • dcca21abjukebox#8 Move copies and queue logic into their topicsmre
  • 3b76651cjukebox#20: update virtual-list README pin and resetKey optionsmre
  • bc09e1e8|||PR jukebox#20: reset virtual lists through resetKey (partial validation)mre
  • a3796dc5Records: live step waits for idlemre