gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2c5eac912c5eac91|||PR ident#38 online state without probe timermre2c5eac91/plugins/web/offline.hl

26.5 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. unacked = {}
  9. replays = {} // 'k<i>' → what ends a replayed entry's wait when its socket closes
  10. live = {} // q → true while a live emit's entry (written before its frame) waits for its ack: the replay leaves it alone
  11. flushing = false
  12. owner = '' // whose the kept copy is (settleWho): the last user logged in
  13. holding = false // an anonymous page over a user's copy: nothing is kept or laid over it
  14. heldBack = false // the server said a queued entry is for another user than the session's
  15. flushAgain = false // an entry was queued while a round ran: the round goes over the queue once more
  16. queueRetryTimer = null // a round that did not fully drain tries again after queueRetryWait
  17. static replayAckTimeout = 20000
  18. static queueRetryWait = 3000
  19. // A DOCUMENT THAT STANDS IN FOR THIS URL (#124): the worker answered an unvisited param page
  20. // with a kept document of the same component, so the seed's parameters are another url's.
  21. // This url's are the truth: they go into the instance, and what they feed is derived again
  22. // here (what only the server can derive stays as that document had it, until a push).
  23. standIn() {
  24. if (client.page == null || client.seed.page == null) { return null }
  25. m = client.router.match(location.pathname)
  26. if (m == null || m.route.component != true) { return null }
  27. mine = JSON.stringify(m.params)
  28. if (mine == JSON.stringify(client.seed.page.params)) { return null }
  29. for (k of m.params.keys()) { client.page.instance[k] = m.params[k] }
  30. client.seed.page.params = m.params
  31. client.patch(client.page.chain, 'page', client.moved(&client.page, m.params.keys()), [])
  32. return null
  33. }
  34. // ---- THE OFFLINE LAYER (COMPONENTS §10) --------------------------------------------
  35. // Live only in an app whose manifest declares `offline = [ … ]`: the seed then says
  36. // which pages it keeps, which emits it may queue, which worker to register, and the
  37. // server's clock at the render. Everything is in ONE IndexedDB database, `hl-offline`:
  38. // state `{ k, members }` under `<component>|<path>`: per member, the freshest value
  39. // this browser was told and the server time it was true at (`{ at, v }`,
  40. // v as JSON) — from the render, from a navigation, from every push
  41. // The shell (and each parent level, and the components composed into them) is kept the
  42. // same way under `@shell|<address>|<component>`, so its keys never meet a page's.
  43. // queue `{ id, event, payload, at, q }`, the id counting up, so the order the entries
  44. // are read in IS the order they were made; `q` is the emit's stable id, the
  45. // same on every try, which the server runs once. A queueable emit on an open socket is
  46. // written here BEFORE its frame goes out and leaves on its ack (sent / ack below)
  47. offlineBoot() {
  48. registerWorker()
  49. store = openStore()
  50. if (store == null) { return null }
  51. settleWho()
  52. if (keptPage()) {
  53. rehydrate()
  54. remember(client.seed.page.state.keys(), client.seed.offline.at)
  55. rehydrateShell()
  56. rememberShell()
  57. rehydrateKids()
  58. rememberKids()
  59. }
  60. client.syncQueued()
  61. // the network came back: reconnect now, not when the backoff says (the queue then
  62. // goes out at once)
  63. window.addEventListener('online', () => { client.reconnectNow() })
  64. return null
  65. }
  66. // WHOSE THE KEPT COPY IS (ticket #125). The seed says who the session is (an opaque value,
  67. // '' for nobody); the copy remembers its OWNER under `@who`: the last user who was logged
  68. // in. A session that expired, or a fresh anonymous one, owns nothing and changes nothing:
  69. // the owner's queue is HELD (not replayed, not dropped) and nothing is laid over or kept
  70. // for the anonymous page. The owner logging in again replays it; ANOTHER user logging in
  71. // forgets the owner's copy. The first user to log in adopts a copy that had no owner.
  72. settleWho() {
  73. rec = done(objects('state', 'readonly').get('@who'))
  74. owner = rec != null ? rec.who : ''
  75. w = client.seed.offline.who
  76. holding = w == '' && owner != ''
  77. if (w == '' || owner == w) { return null }
  78. if (owner == '') {
  79. owner = w
  80. done(objects('state', 'readwrite').put({ k = '@who'; who = w; }))
  81. return null
  82. }
  83. return forget(w)
  84. }
  85. // A FACE CHANGED WHOSE SESSION THIS IS (the ack says so): a log-out forgets the copy, a login
  86. // is settled like a page that arrived under that user
  87. whoChanged(w) {
  88. client.dropKept()
  89. if (w == client.seed.offline.who) { return null }
  90. client.seed.offline.who = w
  91. if (w == '') { return forget('') }
  92. return settleWho()
  93. }
  94. // an explicit log-out: the owner's state, queue and documents all go
  95. forgetOffline() {
  96. client.dropKept()
  97. return forget('')
  98. }
  99. // the state, the queue and the worker's documents go; the copy is now `to`'s. The worker
  100. // keeps the page that stands again, fetched as this session sees it.
  101. forget(to) {
  102. if (store == null || client.seed == null || client.seed.offline == null) { return null }
  103. done(objects('state', 'readwrite').clear())
  104. done(objects('queue', 'readwrite').clear())
  105. done(objects('state', 'readwrite').put({ k = '@who'; who = to; }))
  106. owner = to
  107. holding = client.seed.offline.who == '' && to != ''
  108. sw = navigator.serviceWorker
  109. if (sw != null && sw.controller != null) { sw.controller.postMessage({ t = 'forget'; path = location.pathname + location.search; }) }
  110. client.syncQueued()
  111. return null
  112. }
  113. // is the mounted page one the app keeps?
  114. keptPage() {
  115. return client.page != null && client.seed.offline != null && !holding && client.seed.offline.pages.includes(client.page.key)
  116. }
  117. // THE WORKER, registered once: a page it already controls has it, and the browser
  118. // itself checks the entry script for a new build at every navigation
  119. registerWorker() {
  120. sw = navigator.serviceWorker
  121. if (sw == null || sw.controller != null) { return null }
  122. r = window.__hlAttempt(() => { return sw.register(client.seed.offline.worker, { scope = '/' type = 'module' }) })
  123. if (!r.ok) { console.warn('framework: the offline worker could not be registered — ' + r.error) }
  124. return null
  125. }
  126. openStore() {
  127. if (window.indexedDB == null) { return null }
  128. // A BROWSER'S OPEN CAN STAY PENDING (a loaded Chrome: the request neither succeeds nor fails, W88/W99, Atlas G2):
  129. // boot awaits this store before it connects, so the page never finished hydrating. The open is given 3 s; after
  130. // that the page runs without its offline copy (store null, as when IndexedDB is missing) and a late success is closed.
  131. return new Promise((res, rej) => {
  132. let gaveUp = false
  133. req = indexedDB.open('hl-offline', 1)
  134. timer = setTimeout(() => { gaveUp = true res(null) }, 3000)
  135. req.onupgradeneeded = () => {
  136. db = req.result
  137. db.createObjectStore('state', { keyPath = 'k' })
  138. db.createObjectStore('queue', { keyPath = 'id' autoIncrement = true })
  139. }
  140. req.onsuccess = () => {
  141. if (gaveUp) { req.result.close() return null }
  142. clearTimeout(timer)
  143. res(req.result)
  144. }
  145. req.onerror = () => { clearTimeout(timer) res(null) }
  146. })
  147. }
  148. // one object store, in its own transaction
  149. objects(name, mode) {
  150. return store.transaction(name, mode).objectStore(name)
  151. }
  152. // an IndexedDB request's result; null when it failed
  153. done(req) {
  154. return new Promise((res, rej) => {
  155. req.onsuccess = () => { res(req.result) }
  156. req.onerror = () => { res(null) }
  157. })
  158. }
  159. // WHERE THIS PAGE'S STATE IS KEPT (ticket #123). A member that no route parameter feeds is
  160. // the component's: the same list at `/` and at `/notes/:id`, so it is kept ONCE, under the
  161. // component, and every url of it reads the freshest. A member a route parameter feeds — the
  162. // parameter itself, and every derivation that reads one, transitively — is that url's.
  163. stateKey() {
  164. return client.page.key + '|' + location.pathname + location.search
  165. }
  166. paramFed() {
  167. return fedBy(client.page.key, client.seed.page != null ? client.seed.page.params : null)
  168. }
  169. // the members of component `key` that its route parameters feed (the parameters, and everything derived from them)
  170. fedBy(key, params) {
  171. fed = []
  172. if (params != null) {
  173. for (k of params.keys()) { fed.push(k) }
  174. }
  175. list = client.derivationsOf(key)
  176. let again = true
  177. while (again) {
  178. again = false
  179. for (d of list) {
  180. if (!fed.includes(d.name) && client.feedsFrom(d, fed)) {
  181. fed.push(d.name)
  182. again = true
  183. }
  184. }
  185. }
  186. return fed
  187. }
  188. // KEEP what the server said the named members of the page are, as of `at` (its
  189. // clock), the url's under the url and the others under the component.
  190. remember(names, at) {
  191. if (store == null || !keptPage()) { return null }
  192. fed = paramFed()
  193. byUrl = []
  194. byComponent = []
  195. for (n of names) {
  196. if (fed.includes(n)) { byUrl.push(n) } else { byComponent.push(n) }
  197. }
  198. keepMembers(stateKey(), byUrl, at)
  199. keepMembers(client.page.key, byComponent, at)
  200. return null
  201. }
  202. // A member already kept from a LATER moment is left as it is, so the order the answers
  203. // arrive in does not matter. Read and written in one transaction.
  204. keepMembers(k, names, at, chain = null, root = 'shell') {
  205. if (names.length == 0) { return null }
  206. os = objects('state', 'readwrite')
  207. let rec = done(os.get(k))
  208. if (rec == null) { rec = { k = k; members = {}; } }
  209. let changed = false
  210. for (n of names) {
  211. if (n != '__hlQueued' && n != '__hlQueue' && n != '__hlOnline' && n != '__hlReach') {
  212. was = rec.members[n]
  213. v = chain == null ? JSON.stringify(client.page.instance[n]) : client.shellValue(chain, n, root)
  214. if (v != null && (was == null || was.at <= at)) {
  215. rec.members[n] = { at = at; v = v; }
  216. changed = true
  217. }
  218. }
  219. }
  220. if (changed) { done(os.put(rec)) }
  221. return null
  222. }
  223. // AT BOOT, the kept values that are NEWER than this document are laid over it: a
  224. // document the worker served from its cache is as old as the visit that cached it,
  225. // and what a later push said is the fresher truth. A document the network just
  226. // rendered is newer than everything kept, and nothing is laid over it.
  227. rehydrate() {
  228. fed = paramFed()
  229. names = laidOver(done(objects('state', 'readonly').get(stateKey())), fed, true)
  230. for (n of laidOver(done(objects('state', 'readonly').get(client.page.key)), fed, false)) { names.push(n) }
  231. client.patch(client.page.chain, 'page', names, [])
  232. return null
  233. }
  234. // the members of one kept record that are the url's (`fed`) or not, and newer than the document
  235. // (`chain`: null for the page, else the address of the shell mount they are laid over)
  236. laidOver(rec, fed, ofUrl, chain = null, root = 'shell') {
  237. names = []
  238. if (rec == null) { return names }
  239. for (n of rec.members.keys()) {
  240. e = rec.members[n]
  241. if (e.at > client.seed.offline.at && fed.includes(n) == ofUrl) {
  242. if (chain == null) { client.page.instance[n] = JSON.parse(e.v) } else { client.shellLay(chain, n, e.v, root) }
  243. names.push(n)
  244. }
  245. }
  246. return names
  247. }
  248. // THE SHELL, ITS PARENT LEVELS AND THE COMPONENTS COMPOSED INTO THEM (#341) are kept by the
  249. // page's rules: per member, with the server's time, laid over a cached document at boot only
  250. // when newer. They stand at an address (`chain`: [] the shell, ['^'] the next level, …), under
  251. // `@shell|<address>|<component>` so no key is a page's. A level's members that a route parameter
  252. // feeds are that url's (as the page's are); a composed component's are always the url's, since
  253. // what a host binds into it may come from a parameter.
  254. shellKey(chain, key) {
  255. return '@shell|' + chain.join('/') + '|' + key
  256. }
  257. isLevel(chain) {
  258. for (c of chain) { if (c != '^') { return false } }
  259. return true
  260. }
  261. shellFed(chain, key) {
  262. if (!isLevel(chain)) { return null }
  263. return fedBy(key, client.routeParams()[key])
  264. }
  265. rehydrateShell() {
  266. for (m of client.shellMounts()) {
  267. fed = shellFed(m.chain, m.key)
  268. k = shellKey(m.chain, m.key)
  269. let names = []
  270. if (fed == null) {
  271. names = laidOver(done(objects('state', 'readonly').get(k + '|' + location.pathname + location.search)), [], false, m.chain)
  272. } else {
  273. names = laidOver(done(objects('state', 'readonly').get(k + '|' + location.pathname + location.search)), fed, true, m.chain)
  274. for (n of laidOver(done(objects('state', 'readonly').get(k)), fed, false, m.chain)) { names.push(n) }
  275. }
  276. client.patch(m.chain, 'shell', names, [])
  277. }
  278. return null
  279. }
  280. // what the render gave the shell mounts, kept as of the render's time
  281. rememberShell() {
  282. if (store == null || !keptPage()) { return null }
  283. for (m of client.shellMounts()) { rememberMount(m.chain, m.key, m.names, client.seed.offline.at) }
  284. return null
  285. }
  286. // THE COMPONENTS COMPOSED INTO THE PAGE (#343), at any depth, are kept by the same rules, with the
  287. // same walk (client.pageMounts is collectMounts from the page root): always per url, under
  288. // `@page|<address>|<component>`, so no key is a page's or a shell's. The page root's own members
  289. // are the page's (remember above).
  290. kidKey(chain, key) {
  291. return '@page|' + chain.join('/') + '|' + key
  292. }
  293. rehydrateKids() {
  294. for (m of client.pageMounts()) {
  295. names = laidOver(done(objects('state', 'readonly').get(kidKey(m.chain, m.key) + '|' + location.pathname + location.search)), [], false, m.chain, 'page')
  296. client.patch(m.chain, 'page', names, [])
  297. }
  298. return null
  299. }
  300. rememberKids() {
  301. if (store == null || !keptPage()) { return null }
  302. for (m of client.pageMounts()) { rememberMount(m.chain, m.key, m.names, client.seed.offline.at, 'page') }
  303. return null
  304. }
  305. // KEEP the named members of one mount of the shell (or, with root 'page', of the page's composed components), as of `at`
  306. rememberMount(chain, key, names, at, root = 'shell') {
  307. if (store == null || !keptPage()) { return null }
  308. fed = root == 'page' ? null : shellFed(chain, key)
  309. k = root == 'page' ? kidKey(chain, key) : shellKey(chain, key)
  310. url = k + '|' + location.pathname + location.search
  311. if (fed == null) {
  312. keepMembers(url, names, at, chain, root)
  313. return null
  314. }
  315. byUrl = []
  316. byComponent = []
  317. for (n of names) {
  318. if (fed.includes(n)) { byUrl.push(n) } else { byComponent.push(n) }
  319. }
  320. keepMembers(url, byUrl, at, chain)
  321. keepMembers(k, byComponent, at, chain)
  322. return null
  323. }
  324. // AN EMIT THAT DID NOT REACH THE SERVER. A page the app keeps queues it; any other
  325. // says so. It answers null either way: nothing was answered.
  326. undelivered(event, payload, q) {
  327. if (store != null && client.seed.offline.queue.includes(event)) {
  328. enqueue(event, payload, q)
  329. return null
  330. }
  331. // (a navigation's own `page` emit is not reported: it falls back to loading the
  332. // document, which the worker answers)
  333. 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') }
  334. return null
  335. }
  336. // A FILE WAITS WITH ITS EMIT: IndexedDB keeps a File as it is, so the entry's `files`
  337. // holds them and each one's place in the payload names it, `{ __hlFile = n, name, type,
  338. // size }` (what a page shows of it in `__hlQueue`)
  339. enqueue(event, payload, q) {
  340. done(objects('queue', 'readwrite').add(entryOf(event, payload, q)))
  341. client.syncQueued()
  342. // (an entry added while a round runs is taken by that round's next pass)
  343. if (flushing) { flushAgain = true }
  344. // A LIVE EMIT CAN LAND HERE WITH ITS SOCKET STILL OPEN (crossing() above, when only
  345. // its UPLOAD dropped): nothing closed, so there is no "next open" to replay it on.
  346. // flush() is asked for right away — a no-op with no live socket, same as always.
  347. flush()
  348. return null
  349. }
  350. // the queue row of an emit, its files beside it
  351. entryOf(event, payload, q) {
  352. files = []
  353. kept = []
  354. for (a of payload) {
  355. if (client.isFile(a)) {
  356. kept.push(fileMark(a, files.length))
  357. files.push(a)
  358. } else if (client.isFileList(a)) {
  359. marks = []
  360. let j = 0
  361. while (j < a.length) {
  362. provider = client.uploadsReady()
  363. f = provider != null ? provider.fileAt(a, j) : (hlTypeName(a) == 'Hybrid' ? a[j] : a.item(j))
  364. marks.push(fileMark(f, files.length))
  365. files.push(f)
  366. j = j + 1
  367. }
  368. kept.push(marks)
  369. } else {
  370. kept.push(a)
  371. }
  372. }
  373. return { event = event; payload = JSON.stringify(kept); files = files; at = Date.now(); q = q; who = client.seed.offline.who; }
  374. }
  375. // WRITE BEFORE SEND (#339). A queueable emit about to go out on an open socket is in the queue
  376. // first, one transaction, committed before the frame is sent: a page killed while its socket is
  377. // open and silent (a stalled connection) still has the emit, and the next socket replays it.
  378. // It leaves the queue on its ack (ack below). The replay of it and the ack of it can meet (the
  379. // ack arrived, the page was killed before the delete): the entry then goes out again under the
  380. // same `q`, which the server has kept, and it answers the repeat without running it again.
  381. // While the emit is live the replay and the queue's readers leave it alone (`live`).
  382. // Answers 'sent' (the frame may go out), or 'queued' (the socket was lost while the entry was
  383. // written: it waits for the next one and nothing is sent now).
  384. sent(k, event, payload, q) {
  385. if (store == null) {
  386. unacked[k] = { event = event; payload = payload; q = q; id = null; }
  387. return 'sent'
  388. }
  389. live[q] = true
  390. id = commitRow(entryOf(event, payload, q))
  391. if (id == null) {
  392. // (the write failed: the emit is kept in memory as before, and queued if the socket is lost)
  393. live[q] = null
  394. if (client.socket == null || client.socket.readyState != 1) {
  395. enqueue(event, payload, q)
  396. return 'queued'
  397. }
  398. unacked[k] = { event = event; payload = payload; q = q; id = null; }
  399. return 'sent'
  400. }
  401. if (client.socket == null || client.socket.readyState != 1) {
  402. live[q] = null
  403. client.syncQueued()
  404. return 'queued'
  405. }
  406. unacked[k] = { event = event; payload = payload; q = q; id = id; }
  407. return 'sent'
  408. }
  409. // one row added in its own transaction; its id once the transaction has committed, null when it failed
  410. commitRow(rec) {
  411. return new Promise((res, rej) => {
  412. let tx = null
  413. let req = null
  414. let made = window.__hlAttempt(() => {
  415. tx = store.transaction('queue', 'readwrite')
  416. req = tx.objectStore('queue').add(rec)
  417. return 1
  418. })
  419. if (!made.ok) { res(null) return null }
  420. tx.oncomplete = () => { res(req.result) }
  421. tx.onerror = () => { res(null) }
  422. tx.onabort = () => { res(null) }
  423. })
  424. }
  425. // whether entries made for this user wait in the queue, or a replay is under way
  426. queuedAhead() {
  427. if (flushing) { return true }
  428. let rows = done(objects('queue', 'readonly').getAll())
  429. if (rows == null) { return false }
  430. for (r of rows) { if (r.who == client.seed.offline.who && live[r.q] != true) { return true } }
  431. return false
  432. }
  433. fileMark(f, n) {
  434. return { __hlFile = n name = f.name != null ? f.name : '' type = f.type size = f.size }
  435. }
  436. isFileMark(a) {
  437. return hlTypeName(a) == 'Hybrid' && a.__hlFile != null
  438. }
  439. // A REPLAY GIVES A DROPPED UPLOAD MORE THAN ONE TRY (mission 2026-09-26): the socket
  440. // having just reopened says the network is back, so a stall here reads as congestion,
  441. // not as "offline" — unlike a live emit's `uploadFile` (uploadAll above), which still
  442. // gives up on the first drop, so an app that is genuinely offline queues at once
  443. // instead of waiting out a retry budget it does not need. `uploadFile` resumes from
  444. // what the server already has (`begun.have`), so asking it again is exactly a retry,
  445. // not a restart.
  446. uploadFileReplay(event, index, f, q) {
  447. provider = client.uploadsReady()
  448. if (provider == null) { return { error = 'files could not start because the upload module could not be loaded' dropped = true } }
  449. let up = provider.uploadFile(event, index, f, q)
  450. let misses = 0
  451. while (up.dropped == true) {
  452. misses = misses + 1
  453. if (misses > provider.uploadRetries) { return up }
  454. provider.uploadWait(misses)
  455. up = provider.uploadFile(event, index, f, q)
  456. }
  457. return up
  458. }
  459. // a queued entry's files, sent as the emit's own were (`uploadFile`, under its `q` and
  460. // their places): the payload with every mark replaced by `{ __hlUpload = id }`
  461. uploadKept(event, payload, files, q) {
  462. out = []
  463. for (a of payload) {
  464. if (isFileMark(a)) {
  465. up = uploadFileReplay(event, a.__hlFile, files[a.__hlFile], q)
  466. if (up.error != null) { return up }
  467. out.push({ __hlUpload = up.id })
  468. } else if (hlTypeName(a) == 'Hybrid' && a.length != null && a.length > 0 && isFileMark(a[0])) {
  469. ids = []
  470. for (m of a) {
  471. up = uploadFileReplay(event, m.__hlFile, files[m.__hlFile], q)
  472. if (up.error != null) { return up }
  473. ids.push({ __hlUpload = up.id })
  474. }
  475. out.push(ids)
  476. } else {
  477. out.push(a)
  478. }
  479. }
  480. return { payload = out }
  481. }
  482. // THE SOCKET CLOSED: every queueable emit it had not acked is queued, and a replay it
  483. // was carrying stops (its entry is still in the queue — it leaves only on its ack)
  484. unanswered() {
  485. for (k of unacked.keys()) {
  486. u = unacked[k]
  487. if (u != null) {
  488. unacked[k] = null
  489. client.inflight[k] = null
  490. res = client.pending[k]
  491. client.pending[k] = null
  492. // (a live emit's entry is in the queue already: it is only let go of, and replayed on the next socket)
  493. if (u.id != null) { live[u.q] = null client.syncQueued() } else { enqueue(u.event, u.payload, u.q) }
  494. if (res != null) { res(null) }
  495. }
  496. }
  497. for (k of replays.keys()) {
  498. stop = replays[k]
  499. if (stop != null) {
  500. replays[k] = null
  501. client.pending[k] = null
  502. stop()
  503. }
  504. }
  505. return null
  506. }
  507. // THE REPLAY, when a socket opens: every queued entry, oldest first, as an emit frame on
  508. // that socket; the next goes out when this one is acked, and an entry leaves the queue
  509. // only on its ack. A socket that closes midway stops it, and the next open resumes it.
  510. // A ROUND THAT DID NOT FINISH SCHEDULES ITS OWN NEXT TRY (mission 2026-09-26): a socket
  511. // that stays open the whole time never fires the "next open" above, so a step stuck
  512. // inside `replay()` — an upload, or the ack, whichever gave up — must not depend on one.
  513. // `replay()` itself is bounded (uploadCall's stall guard, and the ack wait's own below),
  514. // so `flushing` always clears; this is what makes a jam at any ONE step a delay, not a
  515. // stop.
  516. flush() {
  517. if (flushing || store == null) { return null }
  518. flushing = true
  519. heldBack = false
  520. let drained = true
  521. let again = true
  522. while (again) {
  523. again = false
  524. flushAgain = false
  525. let rows = done(objects('queue', 'readonly').getAll())
  526. if (rows == null) { rows = [] }
  527. for (r of rows) {
  528. replayingQ = null
  529. // NEVER UNDER ANOTHER USER (#125): an entry waits for the user it was made for; one
  530. // from before users were kept (no user) cannot say whose it is, and is dropped unsent
  531. if (done(objects('queue', 'readonly').get(r.id)) == null) {
  532. // (taken back while this round ran)
  533. } else if (r.who == null) {
  534. done(objects('queue', 'readwrite').delete(r.id))
  535. client.syncQueued()
  536. } else if (r.who != client.seed.offline.who) {
  537. } else if (live[r.q] == true) {
  538. // (a live emit waiting for its ack: its frame is out already)
  539. } else if (flushing && replay(r)) {
  540. done(objects('queue', 'readwrite').delete(r.id))
  541. client.syncQueued()
  542. } else {
  543. flushing = false
  544. drained = false
  545. }
  546. }
  547. if (drained && flushAgain && flushing) { again = true }
  548. }
  549. flushing = false
  550. replayingQ = null
  551. if (!drained && !heldBack) {
  552. if (queueRetryTimer != null) { clearTimeout(queueRetryTimer) }
  553. queueRetryTimer = setTimeout(() => { queueRetryTimer = null flush() }, queueRetryWait)
  554. }
  555. return null
  556. }
  557. // one entry on the socket; true when it was acked. ITS FILES GO UP FIRST, under the
  558. // entry's `q`: an upload a dropped connection cut short goes on where it stopped (and the
  559. // entry stays queued), one the server refuses drops the entry with the error, and one
  560. // whose emit the server already handled is not sent again. THE ACK ITSELF IS BOUNDED
  561. // too (`replayAckTimeout`): a socket the heartbeat has not yet caught, or never will for
  562. // this one, must not hold this promise — and `flush()` — open forever.
  563. replay(r) {
  564. let s = client.socket
  565. if (s == null || s.readyState != 1) { return false }
  566. let payload = JSON.parse(r.payload)
  567. if (r.files != null && r.files.length > 0) {
  568. let sent = uploadKept(r.event, payload, r.files, r.q)
  569. if (sent.dropped == true) { return false }
  570. if (sent.error != null) {
  571. console.error("framework: the queued emit '" + r.event + "' is dropped: the upload of " + sent.error)
  572. return true
  573. }
  574. payload = sent.payload
  575. s = client.socket
  576. if (s == null || s.readyState != 1) { return false }
  577. }
  578. client.nextId = client.nextId + 1
  579. i = client.nextId
  580. f = { t = 'emit'; i = i; event = r.event; payload = payload; }
  581. if (r.q != null) { f.q = r.q replayingQ = r.q }
  582. if (r.who != null) { f.w = r.who }
  583. text = JSON.stringify(f)
  584. k = 'k' + i
  585. return new Promise((res, rej) => {
  586. let settled = false
  587. giveUp = setTimeout(() => {
  588. if (settled) { return null }
  589. settled = true
  590. client.pending[k] = null
  591. replays[k] = null
  592. res(false)
  593. return null
  594. }, replayAckTimeout)
  595. client.pending[k] = (answer) => {
  596. if (settled) { return null }
  597. settled = true
  598. clearTimeout(giveUp)
  599. res(!heldBack)
  600. return null
  601. }
  602. replays[k] = () => {
  603. if (settled) { return null }
  604. settled = true
  605. clearTimeout(giveUp)
  606. res(false)
  607. return null
  608. }
  609. s.send(text)
  610. })
  611. }
  612. ready() { return store != null }
  613. queueable(event) { return client.seed.offline.queue.includes(event) }
  614. ack(k, held = false) {
  615. if (held) { heldBack = true }
  616. u = unacked[k]
  617. unacked[k] = null
  618. replays[k] = null
  619. // A LIVE EMIT'S ENTRY LEAVES ON ITS ACK (not waited for: the delete is asked for, and `live` holds
  620. // the replay off until it is done). An ack that says the entry is for another user's session keeps it.
  621. if (u != null && u.id != null) {
  622. if (held) { live[u.q] = null } else { dropRow(u.id, u.q) }
  623. }
  624. return null
  625. }
  626. dropRow(id, q) {
  627. let tx = null
  628. let r = window.__hlAttempt(() => {
  629. tx = store.transaction('queue', 'readwrite')
  630. tx.objectStore('queue').delete(id)
  631. return 1
  632. })
  633. if (!r.ok) { live[q] = null return null }
  634. tx.oncomplete = () => { live[q] = null }
  635. tx.onerror = () => { live[q] = null }
  636. tx.onabort = () => { live[q] = null }
  637. return null
  638. }
  639. ownerOf(w) {
  640. if (store != null && w != null) { whoChanged(w) }
  641. return null
  642. }
  643. arrived(path) {
  644. if (store != null) { settleWho() }
  645. if (client.page != null && client.seed.offline.pages.includes(client.page.key)) {
  646. remember(client.seed.page.state.keys(), client.seed.offline.at)
  647. rememberShell()
  648. rememberKids()
  649. sw = navigator.serviceWorker
  650. if (sw != null && sw.controller != null) { sw.controller.postMessage({ t = 'keep'; path = path; }) }
  651. }
  652. return null
  653. }
  654. rows() {
  655. if (store == null) { return [] }
  656. records = done(objects('queue', 'readonly').getAll())
  657. if (records == null) { return [] }
  658. out = []
  659. for (r of records) { if (live[r.q] != true) { out.push(r) } }
  660. return out
  661. }
  662. cancel(q) {
  663. if (store == null || q == replayingQ) { return false }
  664. for (r of rows()) {
  665. if (r.q == q) {
  666. done(objects('queue', 'readwrite').delete(r.id))
  667. client.syncQueued()
  668. return true
  669. }
  670. }
  671. return false
  672. }

Branches

Latest commits

  • 2c5eac91|||PR ident#38 online state without probe timermre
  • bf1980f2Merge branch 'v56-day56' into mainIdent
  • 62ae0adf|||PR ident: vendor Hybriel day56mre
  • 0d18abc4Merge branch 'f13-avatar' into mainIdent
  • 2a99730a|||PR ident#37 avatar in hlmre
  • fa4ed25bMerge branch 'f11-upsert' into mainIdent
  • 8f3d9bc9|||PR ident#42 keyed upsert and removemre
  • 675493b1ident#42: editing an identity upserts the one edited row (face editIdentity answers { identity, row }); a create or delete keeps the whole list because the rows' position-dependent parts (default, Delete, Identity n) changemre
  • 45e55303ident#42: an app write patches one row: upsert on create, edit and new secret, one-argument remove on delete; the faces answer the changed app (or the deleted id), not the whole listmre
  • 991641d4Merge branch 'f10-access' into mainIdent
  • e56d8273|||PR ident#34 part 4: access and inbox fixed classesmre
  • df7696dbident#34: tests: access ticks selector quoting fixmre
  • 7215903eident#34: access: the unstyled classes all, app, tick, apptick, plus are dropped; the gate finds the app ticks by input[name=app]mre
  • 69b0a0ceident#34: access: the pick buttons use Style.pickCard instead of class pickmre
  • dc702419Merge branch 'f9-choose' into mainIdent
  • 8caec771|||PR ident#34 restore .choose hookmre
  • 0dbff960Merge branch 'f8-shared' into mainIdent
  • d69665f6|||PR ident#34 part 3: shared look classes (wide, avatar, chip/used, conn, choose, who, inboxlink) moved to statics or droppedmre
  • 3a64dc48ident#34: chipLook: radius as the same var() string (a bare token name in a static does not compile); selector gate selectormre
  • eb039073ident#34: tests: signin and migration find the choice without the classmre