jukebox
All repositories: gitoria
17.5 KB
// THE SESSION LAYER — a port of the archived hl:web's web_session.hl (mission 093,// 252, 255, 261), re-read 2026-09-12. The design is the creator's own from// hybrilior: one cookie holds a random id, the SERVER holds everything else; a// session fans out to every socket that shares the cookie; delivery is a// predicate per socket (here: the app's `audience`).//// THE FILE IS THE SESSION; MEMORY IS A CACHE OF THE ONES IN FLIGHT. A lookup// misses in memory, reads ONE file, revives it. Nothing loads the directory at// boot; a restart is a cold cache, not a wipe. The store pass walks the store// to REMOVE expired files, never to revive, and never all at once: a slice of a few// milliseconds per request (W179: a walk of 392 000 files stalled the one request thread 15-30 s).//// THE FILENAME IS A HASH OF THE ID, NEVER THE ID: a value a client sent must not// become a path, and `ls` on the store must not hand out live ids.//// THREE CLOCKS, all seconds: `maxAge` is how long a session stays VALID after its// last touch for a logged-in session (the cookie's Max-Age too);// anonymous sessions expire after `anonKeep`, with or without app data; `idle` how long it stays RESIDENT in// memory with no live socket (eviction is non-destructive — the file is the// truth — so a short clock is safe); `sweepEvery` how often the sweep may run,// piggybacking on real requests (no timer: a site with no requests has nothing// to sweep). `stampDrift` bounds how far the on-disk `seen` may lag the one in// memory, so an active session does not cost a disk write per asset request.//// `dir` is the store's absolute path, or null for memory only (the app's// `sessionDir = false`). The default the framework hands in is `<project>/.sessions`// — a DOT directory, which the dev watcher skips by construction (measured in the// archive: a store inside the watched tree made every session write a re-analysis).import HlwSession from './session.hl'import { randomToken } from 'hl:http1'import { now } from 'hl:time'import { sha256 } from 'hl:crypto'import { readFile, listDir, exists, writeFile, mkDir, remove, changeTime, stat } from 'hl:fs'String dir = nullNumber maxAge = 1209600Number idle = 900Number sweepEvery = 300Number stampDrift = 60String cookie = 'hlsid'secure = null // null: `Secure` when the request came over https; true: always; false: neverNumber anonMax = 10000 // the most anonymous sessions (nobody logged in) kept; the oldest go first (W124)String domain = '' // the cookie's `Domain` (ticket #44): '' = this host onlyNumber anonKeep = 86400 // seconds any anonymous session keeps its file; the store pass removes older ones (W179)Number slice = 40 // milliseconds of one request the store pass may use (W179)map = {} // id → Session, the resident onespersistedSeen = {} // id → the `seen` last written to disk (write avoidance only)stamped = {} // id → the file's change time when THIS process last read or wrote it (ident#28)lastSweep = 0anonOrder = [] // ids of the anonymous sessions, oldest first (W124 eviction backstop)reported = {} // path → true: a foreign file in the store, said oncequeue = null // session filenames awaiting a slice; full directory entries are never retained (W331)qi = 0 // the next entry of `queue`qGone = 0 // files this pass removed so farqListed = 0 // all directory entries, including foreign ones handled while listinglastPass = 0 // when the last pass began// ---- the store --------------------------------------------------------------------path(sid) {if (dir == null) { return null }return dir + '/' + sha256(sid)}open() {if (dir != null) { mkDir(dir, 448) }lastSweep = now()if (startPass()) { storeSlice() } // the first pass begins at boot (one listing, one slice); a foreign file in a small store is named at oncereturn null}load(sid) {let p = path(sid)if (p == null || !exists(p)) { return null }let stamp = changeTime(p) // taken BEFORE the read: a write that lands between them shows at the next lookuplet raw = readFile(p)if (raw == null || !isSessionText(raw)) { return null }let rec = JSON.parse(raw)if (rec == null || rec.id != sid) { return null }if (expired(rec, now())) { drop(sid) return null }let s = rec > new HlwSession()map[sid] = spersistedSeen[sid] = s.seenstamped[sid] = stampreturn s}// IDENT#28 — THE FILE IS THE TRUTH, MEMORY ONLY A COPY. Another process on the same store (the standby// beside the main one) can write a login into the file while this process holds the session resident.// `refresh` compares the file's change time with the one this process last saw and, when the file is// newer, copies it INTO the resident session (the same object, so every socket holding the handle sees// it). Answers true when it reloaded. A missing or foreign file leaves memory alone.refresh(s) {if (dir == null || s == null || s.id == null) { return false }let p = path(s.id)let stamp = changeTime(p)if (stamp == null || stamp == stamped[s.id]) { return false }let raw = readFile(p)if (raw == null || !isSessionText(raw)) { return false }let rec = JSON.parse(raw)if (rec == null || rec.id != s.id) { return false }let f = rec > new HlwSession()s.user = f.users.data = f.datas.handled = f.handleds.created = f.createds.issuedSig = f.issuedSigs.issuedAt = f.issuedAtif (f.seen > s.seen) { s.seen = f.seen }persistedSeen[s.id] = f.seenstamped[s.id] = stampreturn true}put(s) {let p = path(s.id)if (p == null) { return null }if (!exists(dir)) { mkDir(dir, 448) }// IDENT#28: never put an older memory copy over a newer file that holds a login this one lacksif (s.user == null && stamped[s.id] != null && changeTime(p) != stamped[s.id]) {refresh(s)if (s.user != null) { return null }}writeFile(p, JSON.stringify(s), 384)persistedSeen[s.id] = s.seenstamped[s.id] = changeTime(p)return null}drop(sid) {let p = path(sid)if (p != null) { remove(p) }persistedSeen[sid] = nullstamped[sid] = nullreturn null}// ---- the cookie ----------------------------------------------------------------parseCookies(header) {let out = {}if (header == null) { return out }for (part of header.split(';')) {let eq = part.indexOf('=')if (eq > 0) { out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim() }}return out}// `https` is whether THIS request came over https (TLS on the server, or X-Forwarded-Proto); the app's// `sessionSecure` overrides it either way (W124)cookieHeader(sid, https) {let sec = secure == null ? https == true : secure// W138: remember when and with which attributes this session's cookie went out (see `due`)let rec = sid != null ? map[sid] : nullif (rec != null) {rec.issuedSig = signature(sec)rec.issuedAt = now()save(rec)}return cookie + '=' + sid + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + maxAge + (domain != '' ? '; Domain=' + domain : '') + (sec ? '; Secure' : '')}// W138 (gitoria#24, creator rule): a short signature of the cookie's attributessignature(sec) {return cookie + '|' + domain + '|/|' + (sec ? 'S' : '-') + '|Lax'}// W138: does a session's cookie need to go out again? Yes when it was never issued, was issued// with other attributes (a Domain added since), or was// last issued more than a day ago (Chrome caps a cookie's lifetime at 400 days, and logins do not expire).// Anonymous sessions that carry a cookie count too (ident#28: a cookie issued with an old short Max-Age is replaced within a day of its next request); a request// with no cookie has no session here and gets none (lazy sessions).due(s, https) {if (s == null || s.id == null) { return false }let sec = secure == null ? https == true : securereturn s.issuedSig != signature(sec) || now() - s.issuedAt >= 86400000}// ---- the map ---------------------------------------------------------------------// the session a cookie header names: resident, or revived from its file; null when// it names none (no cookie, or an id nobody knows — that browser is anonymous)resolve(cookieHeader) {let ids = cookieValues(cookieHeader)if (ids.length == 0) { return null }if (ids.length == 1) { return byId(ids[0]) }// W137 (gitoria#24): a browser can hold two cookies of the session's name (an old host-only one and a// newer one with the Domain) and sends both. The first that belongs to a signed-in session wins, else// the first that belongs to any known session, else none.let first = nullfor (id of ids) {let s = lookup(id)if (s == null) { continue }if (s.user != null) { first = s break }if (first == null) { first = s }}if (first == null) { return null }touch(first)return first}// every value the Cookie header carries under the session's name, in the order sentcookieValues(header) {let out = []if (header == null) { return out }for (part of header.split(';')) {let eq = part.indexOf('=')if (eq > 0 && part.slice(0, eq).trim() == cookie) { out.push(part.slice(eq + 1).trim()) }}return out}// W137: the extra headers an answer carries when the request held the session's name more than once and// `s` is the session chosen among them: the chosen id again with the app's cookie attributes (Domain// included) under 'Set-Cookie', and, only when the app's cookie has a Domain, a host-only expiry under// 'set-cookie' (a second header line: the server writes one line per key, and the two keys differ in// case only). Without a Domain the expiry would delete the chosen cookie itself.repair(cookieHeaderText, s, https) {let out = {}if (s == null || s.id == null) { return out }let many = cookieValues(cookieHeaderText).length > 1if (!many && !due(s, https)) { return out }out['Set-Cookie'] = cookieHeader(s.id, https)if (many && domain != '') { out['set-cookie'] = expiry(https) }return out}// the same name, no Domain, gone at once: removes a stray host-only cookieexpiry(https) {let sec = secure == null ? https == true : securereturn cookie + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0' + (sec ? '; Secure' : '')}// for /__hl/adopt, which sets a new id and chooses nothing: the host-only strays are expired so the new// cookie is the only one of its namestrays(cookieHeaderText, https) {let out = {}if (domain != '' && cookieValues(cookieHeaderText).length > 1) { out['set-cookie'] = expiry(https) }return out}byId(sid) {let s = lookup(sid)if (s == null) { return null }touch(s)return s}lookup(sid) {if (sid == null) { return null }let s = map[sid]if (s == null) { s = load(sid) } else { refresh(s) }return s}// SESSIONS ARE LAZY (W124): a visitor with no cookie has NO session — `fresh()` hands a transient// one (no id, not in the map, nothing on disk) that a page renders with or a face writes to. Only a// session that GOT something (a login, `data`, an upload) is `adopt`ed: it gets its id, goes into the// map and onto disk, and the caller sets the cookie. A flood of cookie-less requests so costs nothing,// and the anonymous ones that were adopted are capped (`anonMax`, oldest first).fresh() {return new HlwSession(created = now(), seen = now())}// A NEW SESSION WITH AN ID, in the map and on disk (the call W124 removed and apps used): `adopt(fresh())`.// The caller sets the cookie (`cookieHeader(s.id)`).mint() {return adopt(fresh())}// does the session hold anything worth a cookie and a file?hasContent(s) {return s != null && (s.user != null || s.data.keys().length > 0)}adopt(s) {maybeSweep([])if (s.id == null) { s.id = randomToken(32) }map[s.id] = sput(s)if (s.user == null) {anonOrder.push(s.id)if (anonOrder.length > anonMax) { evictAnon() }}return s}// ROTATE (W120): the session `s` gets a NEW id — its user, data and handled list move with it// (it is the same record, only the id changes), the old id's file and memory entry are deleted so a// planted id is anonymous from now on. Answers the old id. The caller tells the browser (cookie).move(s) {let old = s.idlet sid = randomToken(32)map[old] = nulldrop(old)s.id = sids.rotating = falses.seen = now()map[sid] = sput(s)let i = anonOrder.indexOf(old)if (i >= 0) { anonOrder[i] = sid }return old}// an upload (no content yet) is adopted at once; a face's session only when hasContent()evictAnon() {let over = anonOrder.length - anonMaxlet keep = []let n = 0for (id of anonOrder) {let s = map[id]if (s == null || s.user != null) { continue }if (n < over) {drop(id)map[id] = nulln = n + 1} else {keep.push(id)}}anonOrder = keepreturn null}// ONE WRITE PATH for the stamp: every request or frame that presents a session// moves `seen`; the file follows only when it has drifted `stampDrift` secondstouch(s) {refresh(s)s.seen = now()if (dir != null && s.id != null) {let last = persistedSeen[s.id]if (last == null || s.seen - last >= stampDrift * 1000) { put(s) }}return null}// what a face wrote (login, a cart) reaches the file now, not at the next driftsave(s) {if (s != null && s.id != null && map[s.id] != null) { put(s) }return null}// The store pass and cold lookup share the login/anonymous validity clocks.expired(Hybrid rec, Number at) {return rec.seen <= at - (rec.user != null ? maxAge : anonKeep) * 1000}// ---- the sweep -------------------------------------------------------------------// `live` is the set of session ids with an open socket — those are never evictedmaybeSweep(live) {let listed = falseif (now() - lastSweep >= sweepEvery * 1000) { listed = sweep(live) }if (queue != null && !listed) { storeSlice() } // the request that listed the directory does no slice tooreturn null}sweep(live) {lastSweep = now()let cutoff = now() - maxAge * 1000let cold = now() - idle * 1000let evicted = 0let expired = 0let next = {}for (k of map.keys()) {let s = map[k]if (s == null) {// dropped earlier} else if (s.seen <= cutoff && !(refresh(s) && s.seen > cutoff)) {drop(k)expired = expired + 1} else if (dir != null && s.seen <= cold && !live.includes(k)) {persistedSeen[k] = nullevicted = evicted + 1} else {next[k] = s}}map = next // a fresh hybrid: the compaction (archive, mission 261)if (evicted + expired > 0) {console.log('sessions: sweep — evicted ' + evicted + ', expired ' + expired + ', ' + map.keys().length + ' resident')}// a new pass over the files on disk starts when none runs and the last began long enough agoif (dir != null && queue == null && exists(dir) && now() - lastPass >= sweepEvery * 12000) { return startPass() }return false}startPass() {if (dir == null || queue != null || !exists(dir)) { return false }lastPass = now()queue = []qListed = 0for (e of listDir(dir)) {qListed = qListed + 1if (!isSessionName(e.name) || e.type != 'file') { foreign(e) } else { queue.push(e.name) }}qi = 0qGone = 0return true}// W179: ONE SLICE of the store pass, as many files as fit in `slice` milliseconds, then the request goes on.// A file whose change time is newer than the shortest clock is skipped without being read. Of the others:// a session with a user goes when its `seen` is past `maxAge`; every anonymous session goes// when older than `anonKeep`, including one with app data. A resident session is never touched.storeSlice() {let t0 = now()let young = t0 - (anonKeep < maxAge ? anonKeep : maxAge) * 1000let n = queue.lengthlet done = 0while (qi < n && (done % 64 != 63 || now() - t0 < slice)) {name = queue[qi]queue[qi] = null // release the processed filename while the rest of the pass waitsqi = qi + 1done = done + 1p = dir + '/' + namest = stat(p)raw = st != null && st.mtime <= young ? readFile(p) : nullif (raw != null && isSessionText(raw)) {rec = JSON.parse(raw)dead = expired(rec, t0)if (dead && map[rec.id] == null) {remove(p)persistedSeen[rec.id] = nullqGone = qGone + 1}}}if (qi >= n) {console.log('sessions: store pass done — ' + qListed + ' file(s) looked at, ' + qGone + ' removed')queue = null}return null}// ---- what the store holds that is not a session -----------------------------------// A FILE THAT IS NOT A SESSION IS SKIPPED, NEVER PARSED. The store is a directory an// operator can put anything into (a marker, an editor's backup, a copy), and// `JSON.parse` aborts the program on text that is not JSON — at the boot sweep that was// the whole server, before it served anything (ticket #26). Every file this layer// writes is named by a sha256 (64 lowercase hex characters) and holds a Session's JSON,// whose keys come out in the order the Session class declares its fields (older stores wrote them sorted, so a file opening with `{"created":` is still a session); a session file is a JSON object that carries the keys `created` and `seen`. `writeFile` renames a// finished temp file over the target, so a torn session file cannot occur. A file that// is not that shape is left where it is, and said once.isSessionName(name) {if (name.length != 64) { return false }for (c of name.split('')) {if (!'0123456789abcdef'.includes(c)) { return false }}return true}isSessionText(raw) {let t = raw.trim()return t.startsWith('{"') && t.endsWith('}') && t.includes('"created":') && t.includes('"seen":')}foreign(e) {if (reported[e.path] == null) {reported[e.path] = trueconsole.log('sessions: skipped ' + e.path + ' — not a session file (the store names its files by a hash and writes JSON); it is left where it is')}return null}
Branches
Latest commits
- 10f8a8c8Merge branch 'code-order' into mainJukebox
- 204fc828Merge branch 'day72' into mainJukebox
- 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
- 33072bb5|||PR Record day72 gates and Chrome proofmre
- 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
- 6422a020Sync media-player at 51c3818mre
- b582ba1cVendor complete Hybriel day72 plugin setmre
- 02dccbc9Merge branch 'records-1119' into mainJukebox
- a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
- fc7db075Merge branch 'reconnect-retry' into mainJukebox
- ac6f4c6fL2: plain declaration for a in pickedNextmre
- 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
- 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
- 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
- 1f0cd77bMerge branch 'records-day41' into mainJukebox
- 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
- 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
- 04f5d9d5Merge branch 'day41' into mainJukebox
- 8ed6da45|||PR README: media-player pin df9e7dfmre
- d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre