gitoriaLog in with ident

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit20e09d8920e09d89Merge t18 (tracker#18 delta sync) into main (mission 070): conflicts README/STATUS/show.hl/project.hl/browser.mjs, both sides kept; pageShowOf summary = summaryOfmre20e09d89/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

  • 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
  • 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
  • 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
  • 25a50bc4tracker#26 (mission 059): titles from a filmography are completed — on open (skeleton, step-wise face showComplete, no reload) and by the in-app details repair (resumes, TMDB-paced, series in parts); cast from TMDB credits; gate 231, tests/realdata-026.mjs, README + STATUSmre
  • f14db671tracker#22-#25 (mission 058): episode air dates, season check = all episodes watched, movie watched check (+ /my/movies count), /genres/<genre> pages (movies + series, newest first, paginated); gate 238, tests/realdata-058.mjs, README + STATUSmre
  • 1704ec45tracker#17 (mission 057): season caret down/up, skeleton rows while a season loads, sessionless showSeasonEpisodes face (no page re-mount), client-only close; gate 214, tests/realdata-057.mjs, README + STATUSmre
  • f2fe3e36mission 056: README + STATUS (merge, fixes, Hybriel 8590df63, real-data check), tests/realdata-056.mjs, tools/check-public-slugs.hlmre
  • f40c250emission 056: re-vendor hybriel master 8590df63 (#121, #122); an adult title's page is Not found for non-followers; gate: leave the page before stopping the servermre
  • 2b7fdd6cmission 056: signed-out header one row on phones ("Log in", nowrap), backfill skips adult titles' posters, gate checksmre
  • 2c53d5efMerge branch 't16-person' (tracker#16 person pages) into main; filmography shows only public titles (054 adult flag), gate race fix (backfill start line)mre
  • c171227emission 054: hide adult/unknown titles from the public lists and the search; in-app adult-flag backfill (TMDB details + poster per title, resumes), gate + real-data proofmre
  • 139fafd8tracker#16: short bio (4 lines, click = all), real-data check script, README + STATUSmre
  • 93be9476tracker#16: person pages /person/<slug> with the filmography fetched from TMDB on the first visit (step by step), gatemre
  • 47a3cae6STATUS: mission 053 merge commit idsmre
  • dcc5eecaMerge branch 't14-search'mre
  • 03edc783Merge branch 't15-tvmaze'mre
  • 71b46345tracker#15: numbering check by date or title, placeholder titles in other languages, docs + real-data proofmre