gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/web/offline.hl

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

Branches

Latest commits

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