gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit84e1b3e184e1b3e1tracker: reports 025 + 026mre84e1b3e1/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

  • 84e1b3e1tracker: reports 025 + 026mre
  • dc40d859tracker#31 (mission 026): duplicate titles merged — the 68 type+tmdbId pairs held by 157 records were the old tracker's (all migrated); merge.hl repair job (own clock, before the TMDB jobs) keeps one keeper per title (follows/watches > old short id > oldest), moves follows, watches, seasons, cast, credits, timelines, tombstones the rest (mergedInto, never deleted), slugs + short ids 301 to the keeper; stray seasons merged into their listed twin (Reacher S3 watches) or linked when watched; search import re-checks before its put; deploy.sh waits up to 90 s for 200; real copy 68 -> 0 dup ids, az5b2 follows/watches equal; gates 342/0, 32/0, 52/0mre
  • 2667da05tracker#30 (mission 025): /my/ pages from slim cached title cards, episode rows and watch sets (after the jobs /my/series 1.8 s -> 0.06 s, /my/unwatched 4.1 -> 0.18 s); timeline page shows its name once; franchise widget under the poster/title; movies with TV leftovers (First Contact) go through the details repair; tools/count-tmdb-ids.hl; gates 327/0, 52/0, 32/0mre
  • 3909810dantcolony#40: mission references in README/STATUS/docs point to the moved missionsmre
  • e63b1d28antcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 1cda451dtracker: Hybriel master 190aa11d (#127 both shapes, GC correctness fc838894) — conductor adopts despite /my/series 2.4x after jobs (memory 8.0 → 1.7 GB boot); see reports/071mre
  • c1fa2f2etracker (mission 071): Hybriel master 190aa11d measured on the real copy vs the live binary 8590df63 — NOT adopted (after the first-start jobs /my/series 2.4x slower, /series 1.6x, RSS swings 7.4-12.2 GB; fresh it is flat at 1.7-2.2 GB and /my/unwatched faster), vendor stays 8efba065, candidate kept in .scratch/w071/vendor-190aa11d; tests/kinds.mjs: collection seed off (its TMDB request broke check 1 in 1 of 4 runs); tests/realdata-071.sh + realdata-071-bench.mjs + tools/realdata-071-table.py; README + STATUS (numbers, how to repeat); gates 325/0, 32/0, 50/0mre
  • 8081350atracker docs (mission 070): README (summary, Config HL_GC_BYTES — kept at Hybriel's default, the 256 MiB setting is taken out of docker-compose.yml again: the jobs grew to 12+ GB with it too, see STATUS), Test (three gates), Deploy (first start ~50 min: kinds then seed, restart once after collections done, memory numbers), Vendored Hybriel 8efba065 + #48 audit, Files; STATUS mission 070 entry (merges, migrated counts, lambda audit, gates, RSS old vs new, how to repeat, open points); docs/kinds.md + docs/franchises.md job order; tests/realdata-070-*.sh, tools/count-migrated.hl, tools/ref-params.py, tools/lambda-audit.pymre
  • 1ad19c8ctracker: re-vendor Hybriel master 8efba065 (#126 GC by bytes, #48 lambda parameters copy) (mission 070): bin/hybriel sha256 50361e95…, plugins core crypto data fetch fs http http1 mpackdb proc smtp time web; lambda audit: 13 lambdas change a passed record/list (11 through a local alias), no caller relies on it — unchanged; 319 read-only lambda parameters get & (no copy per call: /my/schedule 2.35 → 0.46 s, /my/unwatched 13.7 → 5.7 s on the real copy); /my/unwatched one merge sort instead of n² inserts; docker-compose HL_GC_BYTES=268435456; deploy.sh runs kinds.mjs + franchises.mjs too (default ports 8700–8710); tests/realdata-070.mjs; gates browser 325/0, kinds 32/0, franchises 50/0mre
  • 46b21389tracker (mission 070, conductor): the sync never destroys migrated data — the one-time summary step MOVES a copied summary to migratedSummary (marker summaries-moved.txt) instead of clearing it; a migrated record's first title/genres/homepage/tagline TMDB replaces → migratedTitle/migratedGenres/migratedHomepage/migratedTagline, a migrated season's/episode's title/summary → migratedTitle/migratedSummary (set once); tests/peek-shows.hl prints them; gate 325/0mre
  • 749019b0Merge t19 (tracker#19 franchises + timelines) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs/faketmdb.mjs, both sides kept; franchise/timeline pages get #20's typed heading (Franchise | …, Timeline | …), their title links via titlePath (/movies|/series|/shows); the collection seed waits for repair, kinds and credits too; franchises.mjs URLs + 2 new checks; gates browser 323/0, kinds 32/0, franchises 50/0mre
  • daf49feaMerge t20 (tracker#20 typed headings + #21 series/shows split) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/search.hl/components/search.hl/browser.mjs/faketmdb.mjs, both sides kept; clock order backfill → repair → kinds → credits; withDetailsFields stores tmdbType + kind; gates: browser.mjs URLs → /series|/movies, typed h1 selectors; kinds.mjs repair/credits off, fixture name = seed name; browser 323/0, kinds 32/0mre
  • 20e09d89Merge t18 (tracker#18 delta sync) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs, both sides kept; pageShowOf summary = summaryOfmre
  • f83571c3tracker#18 (mission 067): daily sync by change lists — TMDB /tv|movie/changes (since the stored day, paged) + TVmaze /updates/shows → only our changed titles (followed: full step, unfollowed: light step — changed seasons, no TVmaze), full walk on first run / gap > 14 days / failed list; show record refreshed (title, tmdbSummary, tagline, status, genres …; renamed titles re-indexed); summary = the creator's own text (page: summary > tmdbSummary > tvmazeSummary), one-time clear of copied summaries (9,647 on the live copy); gate 261, tests/realdata-018*.mjs, README + STATUSmre
  • 1ed5457etracker#20 + #21 (mission 068): typed headings "<Type> | <name>" in type colours; TV titles split into Series (/series) and Shows (/shows) by TMDB type + Reality/Talk/News genres — kind stored by sync/import/adult backfill + new kind backfill (resumes), /movies/<slug>, /shows/<slug> of a series/movie → 301, /my/series + /my/shows, home 5 tiles + 3 rows, search/filmography labels; gates kinds 32 + browser 266, tests/realdata-068.mjs, tools/count-kinds.hl, docs/kinds.md, README + STATUSmre
  • f2b00674Merge t26 (tracker#26 + #28) into main (mission 062): short ids for every new person (castPersonId, guest route), guest stars stored on the title and created as people only when opened (/person/tmdb/<id>?show=<id> → 302), lean watch/follow clicks (showRow a small object, cast/crew from the slug, watches cached per user, face rows only after a season toggle); gate 311, tests/realdata-062.mjs, README + STATUSmre
  • 0553b51ftracker#19 (mission 066): franchises and timelines — tables, /franchises, /franchises/<slug>, /timelines/<slug> (Timeline | Release sort, series by last episode), the Prequel | Timeline | Sequel widget with the franchise above, the creator's editor, TMDB collection seed in the app (resumes, paced); gate tests/franchises.mjs 48/0 + browser.mjs 266/0, tests/realdata-066.mjs, docs/franchises.md, README + STATUSmre
  • fa1f9dfatracker#29 (mission 063): unwatched check muted grey outline + check (accent only on hover), watched stays solid — no code regression, the accent outline read as ticked; gate checks real checks visibly (computed style + screenshot pixel) on /my/unwatched, show, movie, /my/movies; gate 266, tests/realdata-063.mjs, README + STATUSmre
  • 10bb3f93tracker#28 (mission 061): full cast (all seasons, main cast by episodes, guest stars) + crew (created by, directed by, written by, screenplay, story, music) — stored by the details completion, the daily sync, the search import (one details request) and a background credits job (resumes, RSS limit); show page collapsed after 20 with client-side Show all; showBySlug via a slug map; gate 249, tests/realdata-028.mjs, README + STATUSmre
  • d8b12d67tracker#27 (mission 060): short ids for movies, series and persons — old 702 kept (data/old-short-ids.json), new random [a-z0-9]{5} unique across both, claimed at creation, background backfill (resumes), shown under poster/photo, /<shortId> → 301; gate 259, tests/realdata-060*, README + STATUSmre