gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchf2-api-bugs26117255|||PR apps API: review comments on files with spaces in their namemref2-api-bugs/plugins/web/offline.hl

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

Branches

Latest commits

  • 26117255|||PR apps API: review comments on files with spaces in their namemre
  • b8796cecMerge branch 'f1-broken-json' into mainGitoria
  • 2f2959c5|||PR apps API: broken JSON body gives 400 invalid_json, not 500mre
  • f7c6ca07Merge branch 'ident-chooser-selector' into mainGitoria
  • 691abb8e|||PR tests: find ident identity choice without the removed .choose classmre
  • 16a3530fMerge branch 'heap-revert' into mainGitoria
  • 220a80e0|||PR Remove temporary /__heap route and heap helper; logmre
  • 13f0c342Merge branch 'hl25-records' into mainGitoria
  • a002ecb7|||PR records: HL25 report, heap helper, logmre
  • 2492a55cTemporary keyed /__heap route for the live memory snapshotmre
  • fefaedd2log: tracker PR-only, HL25 startedmre
  • 21aa57calog: parkmre
  • e9f950a8reports: G25c soakmre
  • a7783686log: deploy 9f41ffcmre
  • 9f41ffc1log: W30b mergedmre
  • bef635c1Merge branch 'w30b'mre
  • 15b996a5Org list: keyed rows by @id, newest first, concat instead of hand loopmre
  • c4f6d9e3reports: G25c growth huntmre
  • b88e39f1log: privacy cleanup donemre
  • bfd7826ddocs: neutral example organisation namemre