jukebox
All repositories: gitoria
13.4 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 boot sweep walks the store// once to REMOVE expired files, never to revive.//// 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 (the cookie's Max-Age too); `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 } 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 onlymap = {} // id → Session, the resident onespersistedSeen = {} // id → the `seen` last written to disk (write avoidance only)lastSweep = 0anonOrder = [] // ids of the anonymous sessions, oldest first (W124 eviction backstop)reported = {} // path → true: a foreign file in the store, said once// ---- the store --------------------------------------------------------------------path(sid) {if (dir == null) { return null }return dir + '/' + sha256(sid)}open() {if (dir != null) { mkDir(dir, 448) }lastSweep = now()if (dir != null) {let n = sweepStore(now() - maxAge * 1000)if (n > 0) { console.log('sessions: boot sweep removed ' + n + ' expired session file(s) from ' + dir) }}return null}load(sid) {let p = path(sid)if (p == null || !exists(p)) { return null }let raw = readFile(p)if (raw == null || !isSessionText(raw)) { return null }let rec = JSON.parse(raw)if (rec == null || rec.id != sid) { return null }let s = rec > new HlwSession()map[sid] = spersistedSeen[sid] = s.seenreturn s}put(s) {let p = path(s.id)if (p == null) { return null }if (!exists(dir)) { mkDir(dir, 448) }writeFile(p, JSON.stringify(s), 384)persistedSeen[s.id] = s.seenreturn null}drop(sid) {let p = path(sid)if (p != null) { remove(p) }persistedSeen[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 signed-in 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 are not refreshed.due(s, https) {if (s == null || s.id == null || s.user == 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) }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) {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 sweep -------------------------------------------------------------------// `live` is the set of session ids with an open socket — those are never evictedmaybeSweep(live) {if (now() - lastSweep >= sweepEvery * 1000) { sweep(live) }return 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) {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)let dropped = 0if (dir != null) { dropped = sweepStore(cutoff) }if (evicted + expired + dropped > 0) {console.log('sessions: sweep — evicted ' + evicted + ', expired ' + expired + ', ' + dropped + ' file(s) removed, ' + map.keys().length + ' resident')}return null}sweepStore(cutoff) {let gone = 0if (!exists(dir)) { return gone }for (e of listDir(dir)) {let raw = isSessionName(e.name) && e.type == 'file' ? readFile(e.path) : nullif (raw != null && !isSessionText(raw)) { raw = null }if (raw == null) { foreign(e) }if (raw != null) {let rec = JSON.parse(raw)if (rec != null && rec.seen <= cutoff) {remove(e.path)persistedSeen[rec.id] = nullgone = gone + 1}}}return gone}// ---- 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
- 06c548d6jukebox JB15: report, log linemre
- 980859cbjukebox JB15 (jukebox#15): the now-playing overlay on a short screen (tablet or phone on its side) gave the queue 12 to 100 px because the big cover took the room; the cover now shrinks with the screen height and goes away under 41rem, the queue keeps 3+ rows; gate tests/jb15.mjs at 8 sizesmre
- 9efc40ffjukebox#12 #14: Grok session 1793246574527-181160mre
- 7d58b36ejukebox JB13 (jukebox#13): Next and Previous ask for the songs after / before the current song's id in the current order, not for place + 1; gate tests/jb13.mjs checks Next with the queue down to one song after the order changedmre
- 51358794jukebox JB14 (jukebox#14): the Songs screen opens sorted the way it was left (kept on the server in storage/ui.json), the sort control shows the sort the rows really have (selected options, autocomplete off); gate tests/jb14.mjsmre
- cc68a063jukebox JB13 (jukebox#13): a tapped song plays the song that was tapped, found by its id in the list as it is now (not by its row number, which counted plays move); the queue goes on from its place there, the rows refresh on the tap; gate tests/jb13.mjs (songs by plays, favourites)mre
- 88d3d5c1jukebox JB12b (jukebox#12): the scroll handle is big (2.75rem x 4rem, accent colour, grip) and drawn on every device, no media query; native bar hidden; gate tests/touch.mjs checks the drawn width with and without touchmre
- b58e4495jukebox JB11 (jukebox#11): the next song starts in the ended event on the same audio element, so it also starts with the screen locked; gate tests/jb11.mjs (hidden tab, no frames)mre
- 12a26233jukebox JB12 (jukebox#12): the long lists get a scroll handle a finger can use on touch screens (44 px tap area, slim look, drag through all rows), gate tests/touch.mjsmre
- 0f2157a9jukebox JV1: onto Hybriel set-day27b: readBytes and stat for /stream and the mp3 tags (no dd, head or tail), startup fault exits 1, fs and mpackdb plugins re-vendored; songs with a comma in the title are indexed againmre
- 63d0f2eejukebox ST1 (jukebox#2): styles of main, songs and search moved into their own Style blocks (styles.hl 81 to 8 rules, pixel-identical at 390 and 1280); artist and album wait for an hl:web fixmre
- c5b8fde9jukebox JB3b: keyboard gap repro as a reportmre
- 9daebb4bjukebox JB3b: shuffle, now-playing overlay, next and previous, play counting, media session, gates; keyboard left open (Hybriel gap)mre
- 59c1373ejukebox JB3 (work in progress): albums without folder and with disc markers folded, compilations, duplicate songs, own play counter, server-side shuffle queuemre
- 2a4cfc55jukebox: library screens (songs, artists, albums, artist, album, search, favourites), compact player bar, /stream with Range, thumbnails, virtual list vendored, ui gate and real-library checkmre
- 93a44212jukebox: report, numbers of the full scan, notes on the index key rulemre
- bf5167dajukebox: index keys without commas (mpackdb loses them after a reopen), comma fixture and gate checksmre
- 28a82fa2jukebox: README, STATUS, LOG, DECISIONSmre
- d13987dfjukebox: library scanner, ID3 reader, mpackdb database and JSON API, with fixtures and a gatemre