gitoria

calendar

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainf9b8f918Merge branch 'calendar-vendor-day61' into mainAtlasmain/plugins/web/offline.hl

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

Branches

Latest commits

  • f9b8f918Merge branch 'calendar-vendor-day61' into mainAtlas
  • 66341793|||PR Vendor Hybriel day61Atlas
  • 36fc596bMerge branch 'vendor-day59' into mainAtlas
  • b37cc1da|||PR Vendor Hybriel day59Atlas
  • 05665102Merge branch 'vendor-day56' into mainAtlas
  • 687296fb|||PR Vendor Hybriel day56Atlas
  • a6166d4eMerge branch 'hl-standard-3' into mainAtlas
  • 6d0eb3b0|||PR Calendar day add buttons only when signed in (Kunibert minor)Atlas
  • add4b499|||PR Make calendar day actions keyboard accessibleAtlas
  • 79e49b4dMerge branch 'hl-standard' into mainAtlas
  • e9fec7bb|||PR HL-STANDARD clean-up: typed parameters, plain locals, by-reference cacheAtlas
  • eff166a4Re-vendor complete Hybriel plugins and runtime to day44mre
  • cef81394Wait for the DST fixture page instead of an unused socketmre
  • 42434f47Check lazy-session cookies after login with a stored anonymous fixturemre
  • 728e84e3Re-vendor complete Hybriel day41 plugin directoriesmre
  • cbd7ff43Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre
  • 59d1da0acalendar: plain declarations instead of needless let in 9 files (calendar#17): 49 declarations that are never reassigned; reassigned ones and the timer closure's p stay letmre
  • f5415cf9calendar: the Style blocks in the language's nested form (calendar#16): rules named after the View's own elements with their children nested, pseudo-classes and @media nested, merged duplicate select rule; same CSS, shots identical in Chrome at 4 sizesmre
  • edb7c947calendar: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 56+4 failing → 60 passedmre
  • bf8cc0fcStyles move into their components: the shell's styles into main.hl, the events and the editors into the month view's Style block; styles.hl keeps only the theme inherit, the accent and the message line; .gitignore ignores a bin symlink too; tests/styles-shots.mjs for the before/after pixel comparemre