gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit8f1d45428f1d4542tracker#40: superseded collections — a TMDB collection timeline whose titles are all in one curated timeline is hidden (supersededBy; kept: own page + editor finder), set by the collection seed when it makes one and by the curated build (lifted when the cover is gone); partly covered ones join that franchise; no second widget (First Contact: only Star Trek — Prime); gate franchiseseed 26/0, browser 365/0, kinds 32/0, franchises 53/0, check-theme 0; real copy 24 supersededmre8f1d4542/plugins/web/sessions.hl

7.8 KB

  1. // THE SESSION LAYER — a port of the archived hl:web's web_session.hl (mission 093,
  2. // 252, 255, 261), re-read 2026-09-12. The design is the creator's own from
  3. // hybrilior: one cookie holds a random id, the SERVER holds everything else; a
  4. // session fans out to every socket that shares the cookie; delivery is a
  5. // predicate per socket (here: the app's `audience`).
  6. //
  7. // THE FILE IS THE SESSION; MEMORY IS A CACHE OF THE ONES IN FLIGHT. A lookup
  8. // misses in memory, reads ONE file, revives it. Nothing loads the directory at
  9. // boot; a restart is a cold cache, not a wipe. The boot sweep walks the store
  10. // once to REMOVE expired files, never to revive.
  11. //
  12. // THE FILENAME IS A HASH OF THE ID, NEVER THE ID: a value a client sent must not
  13. // become a path, and `ls` on the store must not hand out live ids.
  14. //
  15. // THREE CLOCKS, all seconds: `maxAge` is how long a session stays VALID after its
  16. // last touch (the cookie's Max-Age too); `idle` how long it stays RESIDENT in
  17. // memory with no live socket (eviction is non-destructive — the file is the
  18. // truth — so a short clock is safe); `sweepEvery` how often the sweep may run,
  19. // piggybacking on real requests (no timer: a site with no requests has nothing
  20. // to sweep). `stampDrift` bounds how far the on-disk `seen` may lag the one in
  21. // memory, so an active session does not cost a disk write per asset request.
  22. //
  23. // `dir` is the store's absolute path, or null for memory only (the app's
  24. // `sessionDir = false`). The default the framework hands in is `<project>/.sessions`
  25. // — a DOT directory, which the dev watcher skips by construction (measured in the
  26. // archive: a store inside the watched tree made every session write a re-analysis).
  27. import HlwSession from './session.hl'
  28. import { randomToken } from 'hl:http1'
  29. import { now } from 'hl:time'
  30. import { sha256 } from 'hl:crypto'
  31. import { readFile, listDir, exists, writeFile, mkDir, remove } from 'hl:fs'
  32. String dir = null
  33. Number maxAge = 1209600
  34. Number idle = 900
  35. Number sweepEvery = 300
  36. Number stampDrift = 60
  37. String cookie = 'hlsid'
  38. Boolean secure = false // the app is reached over https: the cookie carries `Secure`
  39. String domain = '' // the cookie's `Domain` (ticket #44): '' = this host only
  40. map = {} // id → Session, the resident ones
  41. persistedSeen = {} // id → the `seen` last written to disk (write avoidance only)
  42. lastSweep = 0
  43. reported = {} // path → true: a foreign file in the store, said once
  44. // ---- the store --------------------------------------------------------------------
  45. path(sid) {
  46. if (dir == null) { return null }
  47. return dir + '/' + sha256(sid)
  48. }
  49. open() {
  50. if (dir != null) { mkDir(dir, 448) }
  51. lastSweep = now()
  52. if (dir != null) {
  53. let n = sweepStore(now() - maxAge * 1000)
  54. if (n > 0) { console.log('sessions: boot sweep removed ' + n + ' expired session file(s) from ' + dir) }
  55. }
  56. return null
  57. }
  58. load(sid) {
  59. let p = path(sid)
  60. if (p == null || !exists(p)) { return null }
  61. let raw = readFile(p)
  62. if (raw == null || !isSessionText(raw)) { return null }
  63. let rec = JSON.parse(raw)
  64. if (rec == null || rec.id != sid) { return null }
  65. let s = rec > new HlwSession()
  66. map[sid] = s
  67. persistedSeen[sid] = s.seen
  68. return s
  69. }
  70. put(s) {
  71. let p = path(s.id)
  72. if (p == null) { return null }
  73. if (!exists(dir)) { mkDir(dir, 448) }
  74. writeFile(p, JSON.stringify(s), 384)
  75. persistedSeen[s.id] = s.seen
  76. return null
  77. }
  78. drop(sid) {
  79. let p = path(sid)
  80. if (p != null) { remove(p) }
  81. persistedSeen[sid] = null
  82. return null
  83. }
  84. // ---- the cookie ----------------------------------------------------------------
  85. parseCookies(header) {
  86. let out = {}
  87. if (header == null) { return out }
  88. for (part of header.split(';')) {
  89. let eq = part.indexOf('=')
  90. if (eq > 0) { out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim() }
  91. }
  92. return out
  93. }
  94. cookieHeader(sid) {
  95. return cookie + '=' + sid + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + maxAge + (domain != '' ? '; Domain=' + domain : '') + (secure ? '; Secure' : '')
  96. }
  97. // ---- the map ---------------------------------------------------------------------
  98. // the session a cookie header names: resident, or revived from its file; null when
  99. // it names none (no cookie, or an id nobody knows — that browser is anonymous)
  100. resolve(cookieHeader) {
  101. return byId(parseCookies(cookieHeader)[cookie])
  102. }
  103. byId(sid) {
  104. if (sid == null) { return null }
  105. let s = map[sid]
  106. if (s == null) { s = load(sid) }
  107. if (s == null) { return null }
  108. touch(s)
  109. return s
  110. }
  111. // a new session, resident and on disk; the caller sets the cookie
  112. mint() {
  113. maybeSweep([])
  114. let sid = randomToken(32)
  115. let s = new HlwSession(id = sid, created = now(), seen = now())
  116. map[sid] = s
  117. put(s)
  118. return s
  119. }
  120. // ONE WRITE PATH for the stamp: every request or frame that presents a session
  121. // moves `seen`; the file follows only when it has drifted `stampDrift` seconds
  122. touch(s) {
  123. s.seen = now()
  124. if (dir != null) {
  125. let last = persistedSeen[s.id]
  126. if (last == null || s.seen - last >= stampDrift * 1000) { put(s) }
  127. }
  128. return null
  129. }
  130. // what a face wrote (login, a cart) reaches the file now, not at the next drift
  131. save(s) {
  132. if (s != null) { put(s) }
  133. return null
  134. }
  135. // ---- the sweep -------------------------------------------------------------------
  136. // `live` is the set of session ids with an open socket — those are never evicted
  137. maybeSweep(live) {
  138. if (now() - lastSweep >= sweepEvery * 1000) { sweep(live) }
  139. return null
  140. }
  141. sweep(live) {
  142. lastSweep = now()
  143. let cutoff = now() - maxAge * 1000
  144. let cold = now() - idle * 1000
  145. let evicted = 0
  146. let expired = 0
  147. let next = {}
  148. for (k of map.keys()) {
  149. let s = map[k]
  150. if (s == null) {
  151. // dropped earlier
  152. } else if (s.seen <= cutoff) {
  153. drop(k)
  154. expired = expired + 1
  155. } else if (dir != null && s.seen <= cold && !live.includes(k)) {
  156. persistedSeen[k] = null
  157. evicted = evicted + 1
  158. } else {
  159. next[k] = s
  160. }
  161. }
  162. map = next // a fresh hybrid: the compaction (archive, mission 261)
  163. let dropped = 0
  164. if (dir != null) { dropped = sweepStore(cutoff) }
  165. if (evicted + expired + dropped > 0) {
  166. console.log('sessions: sweep — evicted ' + evicted + ', expired ' + expired + ', ' + dropped + ' file(s) removed, ' + map.keys().length + ' resident')
  167. }
  168. return null
  169. }
  170. sweepStore(cutoff) {
  171. let gone = 0
  172. if (!exists(dir)) { return gone }
  173. for (e of listDir(dir)) {
  174. let raw = isSessionName(e.name) && e.type == 'file' ? readFile(e.path) : null
  175. if (raw != null && !isSessionText(raw)) { raw = null }
  176. if (raw == null) { foreign(e) }
  177. if (raw != null) {
  178. let rec = JSON.parse(raw)
  179. if (rec != null && rec.seen <= cutoff) {
  180. remove(e.path)
  181. persistedSeen[rec.id] = null
  182. gone = gone + 1
  183. }
  184. }
  185. }
  186. return gone
  187. }
  188. // ---- what the store holds that is not a session -----------------------------------
  189. // A FILE THAT IS NOT A SESSION IS SKIPPED, NEVER PARSED. The store is a directory an
  190. // operator can put anything into (a marker, an editor's backup, a copy), and
  191. // `JSON.parse` aborts the program on text that is not JSON — at the boot sweep that was
  192. // the whole server, before it served anything (ticket #26). Every file this layer
  193. // writes is named by a sha256 (64 lowercase hex characters) and holds a Session's JSON,
  194. // whose keys come out sorted, so it opens with `{"created":`; `writeFile` renames a
  195. // finished temp file over the target, so a torn session file cannot occur. A file that
  196. // is not that shape is left where it is, and said once.
  197. isSessionName(name) {
  198. if (name.length != 64) { return false }
  199. for (c of name.split('')) {
  200. if (!'0123456789abcdef'.includes(c)) { return false }
  201. }
  202. return true
  203. }
  204. isSessionText(raw) {
  205. let t = raw.trim()
  206. return t.startsWith('{"created":') && t.endsWith('}')
  207. }
  208. foreign(e) {
  209. if (reported[e.path] == null) {
  210. reported[e.path] = true
  211. console.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')
  212. }
  213. return null
  214. }

Branches

Latest commits

  • 8f1d4542tracker#40: superseded collections — a TMDB collection timeline whose titles are all in one curated timeline is hidden (supersededBy; kept: own page + editor finder), set by the collection seed when it makes one and by the curated build (lifted when the cover is gone); partly covered ones join that franchise; no second widget (First Contact: only Star Trek — Prime); gate franchiseseed 26/0, browser 365/0, kinds 32/0, franchises 53/0, check-theme 0; real copy 24 supersededmre
  • 7d4b293dtracker#40: "Franchises" in the main menu (desktop header after People, phone sidebar) → /franchises, marked on franchise and timeline pages; gates 365/0, 32/0, 53/0, 24/0, check-theme 0mre
  • 93dfb0batracker#40 (mission 034): the curated franchises — data/franchises.json (17 franchises, 31 timelines, 285 TMDB titles, movies + series, in-universe/release order, 12 TMDB collections attached); lib/franchiseseed.hl + jobs.hl franchiseSeedTick (last start job, imports missing titles via details.hl importWithCredits = the search's Add, one per step paced, then one build; franchiseseed.db: editor changes win, the creator's same-name franchise adopted / timeline left alone, 404 remembered, resumable, idempotent); timeline heads 'N titles · in-universe order' (orderKind) and wrap on a phone; series pages show the widget; new gate tests/franchiseseed.mjs (5th in deploy.sh), the others run with TRACKER_FRANCHISE_SEED=0; gates 365/0, 32/0, 52/0, 24/0, check-theme 0; real copy 196 imported, 0 failed, 7 min, restart unchanged=31mre
  • 96ba683adeploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the scriptmre
  • eb3b9205tracker: report 031mre
  • 9b5d2e89tracker mission 031: README (What it does, Test: four gates + the #32 checks, Files: theme/, new pages), STATUS (real copy, A/B load, how to repeat, open points), LOGmre
  • 39950e4ctracker#32 (mission 031): the WorldAPI theme (theme/ vendored verbatim from layouts.worldapi.org 85b5654; styles.hl inherits it: accent green-dark, type colours 1-6; own base/header rules, row lines, genre-pill and inverted-button frames removed, the season foldable keeps its line; check-theme 21 -> 0, 4th deploy gate; main actions class primary) and the #32 header (theme AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst: desktop brand, search, Series|Shows|Movies|Genres|People, user icon with Unwatched..Settings, Logout; signed out the ident selector, phone the iD icon dropdown; phone menu in the sidebar overlay; marked entry by :has); /find -> /search/<q>, /genres, /people(/<letter>), /settings; main { ContentFirst { slot } } works around the hl:web one-line slot bug; gates 365/0, 32/0, 52/0, check-theme 0mre
  • a386dc92tracker: reports 029 + 030mre
  • 71e0fd7dtracker missions 029 + 030: README (What it does, Files, gate count), STATUS (real-copy numbers, how to repeat, open points), LOGmre
  • d36ea6eatracker#34 + #35 (mission 030): Follow directly under the poster, as wide as the poster (show.hl, styles.hl); the status pill next to a series' title — TVmaze's status (new tvmazeStatus, stored by the sync's TVmaze merge) else TMDB's, TVmaze Ended + TMDB Canceled = Canceled, inverted (filled, dark text, no border), green running / yellow pending / red canceled / muted ended (shows.hl statusOf); the daily delta asks TVmaze's status of an unfollowed series TVmaze's change list names (dailysync.hl syncRunStep, sync.hl syncTvmazeStatus); the status backfill after the details repair (backfill.hl, jobs.hl statusTick; resumable, 550 ms per TVmaze request); gates 354/0, 32/0, 52/0mre
  • 7d7d4487tracker#33 (mission 029): reduced titles — every title TMDB's details never went through this app (no detailsAt, no tmdbSync) is incomplete (shows.hl isIncomplete; the old tracker's migrated rows passed #26's test: 5,697 non-adult on the live copy, 691 series without seasons); the repair job does the visibly reduced first (shows.hl missingParts), the page completes one on open; a title TMDB has no poster for (The Remaining) shows the placeholder; tools/count-incomplete.hl; gate fixtures stand for synced titles (tmdbSync), tests/seed-reduced.hl + #33 checks; gates 347/0, 32/0, 52/0mre
  • 661c2592tracker: report 028mre
  • 27c916fatracker mission 028: README ("Code order", the new file map), STATUS (counts before/after, tests, how to repeat, open), LOGmre
  • d924f398tracker mission 028: comments name the new files (sync.hl, dailysync.hl, backfill.hl, credits.hl, jobs.hl, images.hl …); tools/ref-params.py + tools/lambda-audit.py also scan lib/ (they globbed the root only), lambda-audit counts a plain `x = p` alias like `let x = p`mre
  • 2e89b968tracker mission 028 (code order) 5/5 let: `let` only where a variable is reassigned — 667 never-reassigned lets became plain declarations (project.hl, lib/, components/, tools/, tests/); kept: 264 in loop bodies (a plain declaration there is 'Cannot reassign' on the 2nd pass), 234 reassigned, 27 whose name is also a member/outer/free name (a plain write would rebind it); tools/let-audit.py decides and fixes (README 'Code order'); tests/realdata-m028.{sh,mjs} = the page-output diff on a real copy; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
  • 54796ff2tracker mission 028 (code order) 4/5 thin faces + last copies: the show page's check/follow faces call lib/watches.hl toggleWatched / toggleSeasonWatched (seasonAllWatched moved there) and lib/follows.hl toggleFollowed; both logins (header selector face, /login/callback) share lib/users.hl userOfCode; todayStr/listOf copies in components and the export readers copied into tools/migrate.hl + tools/old-short-ids.hl now once (lib/util.hl, lib/export.hl); gates 342/0, 32/0, 52/0; old-short-ids output byte-identical, migrate output identicalmre
  • 06b078e3tracker mission 028 (code order) 3/5 project.hl is the map: config, routes, wiring and a feature → file index (914 → 258 lines); the background jobs (daily sync run, backfills, details repair, credits job, merge, short ids, collection seed) moved unchanged into lib/jobs.hl (a class: their state is reassigned every step, a static cannot be; one instance made after the server), the login callback into lib/users.hl, poster/photo serving into lib/images.hl, the /shows/<slug> rule into lib/shows.hl showsMovedPath; route handlers are thin wrappers; gates 342/0, 32/0, 52/0, real-copy pages identicalmre
  • 94716fd2tracker mission 028 (code order) 2/5 util + topics: lib/util.hl holds envOr, storageDir, postersDir, profilesDir, newId, hexDigits, todayStr, dateOr, textOr, hasId, listOr, firstOf, sortDesc once (were copied into up to 5 files); tmdbsync.hl split into tmdb.hl (TMDB/TVmaze requests), sync.hl (one title's sync), sync-helpers.hl, backfill.hl; details.hl split into details.hl, credits.hl, credits-helpers.hl (isIncomplete to shows.hl); search-helpers.hl (words, query, ranking, slugs); collections.hl (the TMDB collection seed, out of franchises.hl); deltasync.hl renamed dailysync.hl; no behaviour change: gates 342/0, 32/0, 52/0, real-copy pages identicalmre
  • 186079b0tracker mission 028 (code order) 1/5 move: every root .hl except project.hl into lib/ (styles.hl into components/), import paths only; gates 342/0, 32/0, 52/0; real-copy pages identicalmre
  • 4f47f181tracker: report 027mre