tracker
All repositories: gitoria
19.0 KB
// Offline state and durable emits. The Client handle stays live across navigation;// seed, page and socket are always read from it, never copied into this feature.import { registerFeature } from 'hl:web'client = nullstatic register = () => { return registerFeature('offline', Offline) }replayingQ = null // the `q` of the queued entry whose frame is out and not acked (it cannot be taken back)store = nullunacked = {}replays = {} // 'k<i>' → what ends a replayed entry's wait when its socket closesflushing = falseowner = '' // whose the kept copy is (settleWho): the last user logged inholding = false // an anonymous page over a user's copy: nothing is kept or laid over itheldBack = false // the server said a queued entry is for another user than the session'sflushAgain = false // an entry was queued while a round ran: the round goes over the queue once morequeueRetryTimer = null // a round that did not fully drain tries again after queueRetryWaitstatic replayAckTimeout = 20000static queueRetryWait = 3000// A DOCUMENT THAT STANDS IN FOR THIS URL (#124): the worker answered an unvisited param page// with a kept document of the same component, so the seed's parameters are another url's.// This url's are the truth: they go into the instance, and what they feed is derived again// here (what only the server can derive stays as that document had it, until a push).standIn() {if (client.page == null || client.seed.page == null) { return null }m = client.router.match(location.pathname)if (m == null || m.route.component != true) { return null }mine = JSON.stringify(m.params)if (mine == JSON.stringify(client.seed.page.params)) { return null }for (k of m.params.keys()) { client.page.instance[k] = m.params[k] }client.seed.page.params = m.paramsclient.patch(client.page.chain, 'page', client.moved(&client.page, m.params.keys()), [])return null}// ---- THE OFFLINE LAYER (COMPONENTS §10) --------------------------------------------// Live only in an app whose manifest declares `offline = [ … ]`: the seed then says// which pages it keeps, which emits it may queue, which worker to register, and the// server's clock at the render. Everything is in ONE IndexedDB database, `hl-offline`:// state `{ k, members }` under `<component>|<path>`: per member, the freshest value// this browser was told and the server time it was true at (`{ at, v }`,// v as JSON) — from the render, from a navigation, from every push// queue `{ id, event, payload, at, q }`, the id counting up, so the order the entries// are read in IS the order they were made; `q` is the emit's stable id, the// same on every try, which the server runs onceofflineBoot() {registerWorker()store = openStore()if (store == null) { return null }settleWho()if (keptPage()) {rehydrate()remember(client.seed.page.state.keys(), client.seed.offline.at)}client.syncQueued()// the network came back: reconnect now, not when the backoff says (the queue then// goes out at once)window.addEventListener('online', () => { client.reconnectNow() })return null}// WHOSE THE KEPT COPY IS (ticket #125). The seed says who the session is (an opaque value,// '' for nobody); the copy remembers its OWNER under `@who`: the last user who was logged// in. A session that expired, or a fresh anonymous one, owns nothing and changes nothing:// the owner's queue is HELD (not replayed, not dropped) and nothing is laid over or kept// for the anonymous page. The owner logging in again replays it; ANOTHER user logging in// forgets the owner's copy. The first user to log in adopts a copy that had no owner.settleWho() {rec = done(objects('state', 'readonly').get('@who'))owner = rec != null ? rec.who : ''w = client.seed.offline.whoholding = w == '' && owner != ''if (w == '' || owner == w) { return null }if (owner == '') {owner = wdone(objects('state', 'readwrite').put({ k = '@who'; who = w; }))return null}return forget(w)}// A FACE CHANGED WHOSE SESSION THIS IS (the ack says so): a log-out forgets the copy, a login// is settled like a page that arrived under that userwhoChanged(w) {client.dropKept()if (w == client.seed.offline.who) { return null }client.seed.offline.who = wif (w == '') { return forget('') }return settleWho()}// an explicit log-out: the owner's state, queue and documents all goforgetOffline() {client.dropKept()return forget('')}// the state, the queue and the worker's documents go; the copy is now `to`'s. The worker// keeps the page that stands again, fetched as this session sees it.forget(to) {if (store == null || client.seed == null || client.seed.offline == null) { return null }done(objects('state', 'readwrite').clear())done(objects('queue', 'readwrite').clear())done(objects('state', 'readwrite').put({ k = '@who'; who = to; }))owner = toholding = client.seed.offline.who == '' && to != ''sw = navigator.serviceWorkerif (sw != null && sw.controller != null) { sw.controller.postMessage({ t = 'forget'; path = location.pathname + location.search; }) }client.syncQueued()return null}// is the mounted page one the app keeps?keptPage() {return client.page != null && client.seed.offline != null && !holding && client.seed.offline.pages.includes(client.page.key)}// THE WORKER, registered once: a page it already controls has it, and the browser// itself checks the entry script for a new build at every navigationregisterWorker() {sw = navigator.serviceWorkerif (sw == null || sw.controller != null) { return null }r = window.__hlAttempt(() => { return sw.register(client.seed.offline.worker, { scope = '/' type = 'module' }) })if (!r.ok) { console.warn('framework: the offline worker could not be registered — ' + r.error) }return null}openStore() {if (window.indexedDB == null) { return null }// A BROWSER'S OPEN CAN STAY PENDING (a loaded Chrome: the request neither succeeds nor fails, W88/W99, Atlas G2):// boot awaits this store before it connects, so the page never finished hydrating. The open is given 3 s; after// that the page runs without its offline copy (store null, as when IndexedDB is missing) and a late success is closed.return new Promise((res, rej) => {let gaveUp = falsereq = indexedDB.open('hl-offline', 1)timer = setTimeout(() => { gaveUp = true res(null) }, 3000)req.onupgradeneeded = () => {db = req.resultdb.createObjectStore('state', { keyPath = 'k' })db.createObjectStore('queue', { keyPath = 'id' autoIncrement = true })}req.onsuccess = () => {if (gaveUp) { req.result.close() return null }clearTimeout(timer)res(req.result)}req.onerror = () => { clearTimeout(timer) res(null) }})}// one object store, in its own transactionobjects(name, mode) {return store.transaction(name, mode).objectStore(name)}// an IndexedDB request's result; null when it faileddone(req) {return new Promise((res, rej) => {req.onsuccess = () => { res(req.result) }req.onerror = () => { res(null) }})}// WHERE THIS PAGE'S STATE IS KEPT (ticket #123). A member that no route parameter feeds is// the component's: the same list at `/` and at `/notes/:id`, so it is kept ONCE, under the// component, and every url of it reads the freshest. A member a route parameter feeds — the// parameter itself, and every derivation that reads one, transitively — is that url's.stateKey() {return client.page.key + '|' + location.pathname + location.search}paramFed() {fed = []if (client.seed.page != null && client.seed.page.params != null) {for (k of client.seed.page.params.keys()) { fed.push(k) }}list = client.derivationsOf(client.page.key)let again = truewhile (again) {again = falsefor (d of list) {if (!fed.includes(d.name) && client.feedsFrom(d, fed)) {fed.push(d.name)again = true}}}return fed}// KEEP what the server said the named members of the page are, as of `at` (its// clock), the url's under the url and the others under the component.remember(names, at) {if (store == null || !keptPage()) { return null }fed = paramFed()byUrl = []byComponent = []for (n of names) {if (fed.includes(n)) { byUrl.push(n) } else { byComponent.push(n) }}keepMembers(stateKey(), byUrl, at)keepMembers(client.page.key, byComponent, at)return null}// A member already kept from a LATER moment is left as it is, so the order the answers// arrive in does not matter. Read and written in one transaction.keepMembers(k, names, at) {if (names.length == 0) { return null }os = objects('state', 'readwrite')let rec = done(os.get(k))if (rec == null) { rec = { k = k; members = {}; } }let changed = falsefor (n of names) {if (n != '__hlQueued' && n != '__hlQueue' && n != '__hlOnline' && n != '__hlReach') {was = rec.members[n]v = JSON.stringify(client.page.instance[n])if (v != null && (was == null || was.at <= at)) {rec.members[n] = { at = at; v = v; }changed = true}}}if (changed) { done(os.put(rec)) }return null}// AT BOOT, the kept values that are NEWER than this document are laid over it: a// document the worker served from its cache is as old as the visit that cached it,// and what a later push said is the fresher truth. A document the network just// rendered is newer than everything kept, and nothing is laid over it.rehydrate() {fed = paramFed()names = laidOver(done(objects('state', 'readonly').get(stateKey())), fed, true)for (n of laidOver(done(objects('state', 'readonly').get(client.page.key)), fed, false)) { names.push(n) }client.patch(client.page.chain, 'page', names, [])return null}// the members of one kept record that are the url's (`fed`) or not, and newer than the documentlaidOver(rec, fed, ofUrl) {names = []if (rec == null) { return names }for (n of rec.members.keys()) {e = rec.members[n]if (e.at > client.seed.offline.at && fed.includes(n) == ofUrl) {client.page.instance[n] = JSON.parse(e.v)names.push(n)}}return names}// AN EMIT THAT DID NOT REACH THE SERVER. A page the app keeps queues it; any other// says so. It answers null either way: nothing was answered.undelivered(event, payload, q) {if (store != null && client.seed.offline.queue.includes(event)) {enqueue(event, payload, q)return null}// (a navigation's own `page` emit is not reported: it falls back to loading the// document, which the worker answers)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') }return null}// A FILE WAITS WITH ITS EMIT: IndexedDB keeps a File as it is, so the entry's `files`// holds them and each one's place in the payload names it, `{ __hlFile = n, name, type,// size }` (what a page shows of it in `__hlQueue`)enqueue(event, payload, q) {files = []kept = []for (a of payload) {if (client.isFile(a)) {kept.push(fileMark(a, files.length))files.push(a)} else if (client.isFileList(a)) {marks = []let j = 0while (j < a.length) {f = client.fileAt(a, j)marks.push(fileMark(f, files.length))files.push(f)j = j + 1}kept.push(marks)} else {kept.push(a)}}done(objects('queue', 'readwrite').add({ event = event; payload = JSON.stringify(kept); files = files; at = Date.now(); q = q; who = client.seed.offline.who; }))client.syncQueued()// (an entry added while a round runs is taken by that round's next pass)if (flushing) { flushAgain = true }// A LIVE EMIT CAN LAND HERE WITH ITS SOCKET STILL OPEN (crossing() above, when only// its UPLOAD dropped): nothing closed, so there is no "next open" to replay it on.// flush() is asked for right away — a no-op with no live socket, same as always.flush()return null}// whether entries made for this user wait in the queue, or a replay is under wayqueuedAhead() {if (flushing) { return true }let rows = done(objects('queue', 'readonly').getAll())if (rows == null) { return false }for (r of rows) { if (r.who == client.seed.offline.who) { return true } }return false}fileMark(f, n) {return { __hlFile = n name = f.name != null ? f.name : '' type = f.type size = f.size }}isFileMark(a) {return hlTypeName(a) == 'Hybrid' && a.__hlFile != null}// A REPLAY GIVES A DROPPED UPLOAD MORE THAN ONE TRY (mission 2026-09-26): the socket// having just reopened says the network is back, so a stall here reads as congestion,// not as "offline" — unlike a live emit's `uploadFile` (uploadAll above), which still// gives up on the first drop, so an app that is genuinely offline queues at once// instead of waiting out a retry budget it does not need. `uploadFile` resumes from// what the server already has (`begun.have`), so asking it again is exactly a retry,// not a restart.uploadFileReplay(event, index, f, q) {let up = client.uploadFile(event, index, f, q)let misses = 0while (up.dropped == true) {misses = misses + 1if (misses > client.uploadRetries) { return up }client.uploadWait(misses)up = client.uploadFile(event, index, f, q)}return up}// a queued entry's files, sent as the emit's own were (`uploadFile`, under its `q` and// their places): the payload with every mark replaced by `{ __hlUpload = id }`uploadKept(event, payload, files, q) {out = []for (a of payload) {if (isFileMark(a)) {up = uploadFileReplay(event, a.__hlFile, files[a.__hlFile], q)if (up.error != null) { return up }out.push({ __hlUpload = up.id })} else if (hlTypeName(a) == 'Hybrid' && a.length != null && a.length > 0 && isFileMark(a[0])) {ids = []for (m of a) {up = uploadFileReplay(event, m.__hlFile, files[m.__hlFile], q)if (up.error != null) { return up }ids.push({ __hlUpload = up.id })}out.push(ids)} else {out.push(a)}}return { payload = out }}// THE SOCKET CLOSED: every queueable emit it had not acked is queued, and a replay it// was carrying stops (its entry is still in the queue — it leaves only on its ack)unanswered() {for (k of unacked.keys()) {u = unacked[k]if (u != null) {unacked[k] = nullclient.inflight[k] = nullres = client.pending[k]client.pending[k] = nullenqueue(u.event, u.payload, u.q)if (res != null) { res(null) }}}for (k of replays.keys()) {stop = replays[k]if (stop != null) {replays[k] = nullclient.pending[k] = nullstop()}}return null}// THE REPLAY, when a socket opens: every queued entry, oldest first, as an emit frame on// that socket; the next goes out when this one is acked, and an entry leaves the queue// only on its ack. A socket that closes midway stops it, and the next open resumes it.// A ROUND THAT DID NOT FINISH SCHEDULES ITS OWN NEXT TRY (mission 2026-09-26): a socket// that stays open the whole time never fires the "next open" above, so a step stuck// inside `replay()` — an upload, or the ack, whichever gave up — must not depend on one.// `replay()` itself is bounded (uploadCall's stall guard, and the ack wait's own below),// so `flushing` always clears; this is what makes a jam at any ONE step a delay, not a// stop.flush() {if (flushing || store == null) { return null }flushing = trueheldBack = falselet drained = truelet again = truewhile (again) {again = falseflushAgain = falselet rows = done(objects('queue', 'readonly').getAll())if (rows == null) { rows = [] }for (r of rows) {replayingQ = null// NEVER UNDER ANOTHER USER (#125): an entry waits for the user it was made for; one// from before users were kept (no user) cannot say whose it is, and is dropped unsentif (done(objects('queue', 'readonly').get(r.id)) == null) {// (taken back while this round ran)} else if (r.who == null) {done(objects('queue', 'readwrite').delete(r.id))client.syncQueued()} else if (r.who != client.seed.offline.who) {} else if (flushing && replay(r)) {done(objects('queue', 'readwrite').delete(r.id))client.syncQueued()} else {flushing = falsedrained = false}}if (drained && flushAgain && flushing) { again = true }}flushing = falsereplayingQ = nullif (!drained && !heldBack) {if (queueRetryTimer != null) { clearTimeout(queueRetryTimer) }queueRetryTimer = setTimeout(() => { queueRetryTimer = null flush() }, queueRetryWait)}return null}// one entry on the socket; true when it was acked. ITS FILES GO UP FIRST, under the// entry's `q`: an upload a dropped connection cut short goes on where it stopped (and the// entry stays queued), one the server refuses drops the entry with the error, and one// whose emit the server already handled is not sent again. THE ACK ITSELF IS BOUNDED// too (`replayAckTimeout`): a socket the heartbeat has not yet caught, or never will for// this one, must not hold this promise — and `flush()` — open forever.replay(r) {let s = client.socketif (s == null || s.readyState != 1) { return false }let payload = JSON.parse(r.payload)if (r.files != null && r.files.length > 0) {let sent = uploadKept(r.event, payload, r.files, r.q)if (sent.dropped == true) { return false }if (sent.error != null) {console.error("framework: the queued emit '" + r.event + "' is dropped: the upload of " + sent.error)return true}payload = sent.payloads = client.socketif (s == null || s.readyState != 1) { return false }}client.nextId = client.nextId + 1i = client.nextIdf = { t = 'emit'; i = i; event = r.event; payload = payload; }if (r.q != null) { f.q = r.q replayingQ = r.q }if (r.who != null) { f.w = r.who }text = JSON.stringify(f)k = 'k' + ireturn new Promise((res, rej) => {let settled = falsegiveUp = setTimeout(() => {if (settled) { return null }settled = trueclient.pending[k] = nullreplays[k] = nullres(false)return null}, replayAckTimeout)client.pending[k] = (answer) => {if (settled) { return null }settled = trueclearTimeout(giveUp)res(!heldBack)return null}replays[k] = () => {if (settled) { return null }settled = trueclearTimeout(giveUp)res(false)return null}s.send(text)})}ready() { return store != null }queueable(event) { return client.seed.offline.queue.includes(event) }sent(k, event, payload, q) { unacked[k] = { event = event; payload = payload; q = q; } }ack(k, held = false) {if (held) { heldBack = true }unacked[k] = nullreplays[k] = nullreturn null}ownerOf(w) {if (store != null && w != null) { whoChanged(w) }return null}arrived(path) {if (store != null) { settleWho() }if (client.page != null && client.seed.offline.pages.includes(client.page.key)) {remember(client.seed.page.state.keys(), client.seed.offline.at)sw = navigator.serviceWorkerif (sw != null && sw.controller != null) { sw.controller.postMessage({ t = 'keep'; path = path; }) }}return null}rows() {if (store == null) { return [] }records = done(objects('queue', 'readonly').getAll())return records != null ? records : []}cancel(q) {if (store == null || q == replayingQ) { return false }for (r of rows()) {if (r.q == q) {done(objects('queue', 'readwrite').delete(r.id))client.syncQueued()return true}}return false}
Branches
Latest commits
- 5b3a5693Log: SR1b merged via PR 2, DP71 startedTracker
- 783957c2Merge branch 'sr1-search' into mainTracker
- 792b9652README: search results come from the routeTracker
- fd8570b1|||PR search: one server exchange per keystrokeTracker
- e8f5cbcaLog: SR1 result, SR1bTracker
- 8ad275a4Log/status: tracker 68, SR1Tracker
- f5a06a0fLog: gitoria push setup, SR1Tracker
- d6b109baMission SR1mre
- 608b7558Log: FF1 merged via PR #1mre
- 2939d94cMerge branch 'ff1-gate-failfast' into mainTracker
- c934361a|||PR tests: gates fail fast when the app exits during startmre
- d714ae42Log/status: AP56 closed out, FF1mre
- a429d088Mission FF1mre
- 03bbfba3Log: AP56c causemre
- 24845fe3Log: AP56b result, AP56cmre
- 6a6d71eaLog: gitoria membershipmre
- 8b842dc8Log + CONDUCTOR: gitoria PR switch-onmre
- 6bb7c20estatus: window 2026-11-09mre
- 5db84974Log: Apollo window GO, AP56b started, BS1 copy removedmre
- e84586a7Mission AP56bmre