gitoriaLog in with ident

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainbb64d57cmission 012 (ticket #25 API part): every /api/projects/<x>/… route takes the project's id (12-char record id) as well as its slug, same answers byte for byte; tickets stay under their project, no global /api/tickets/<x>. gate 315/0 (old code: the 13 id checks fail), connect 60/0, live-data copy old vs new 1,484 identical, slug vs id 772 identicalmremain/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

  • bb64d57cmission 012 (ticket #25 API part): every /api/projects/<x>/… route takes the project's id (12-char record id) as well as its slug, same answers byte for byte; tickets stay under their project, no global /api/tickets/<x>. gate 315/0 (old code: the 13 id checks fail), connect 60/0, live-data copy old vs new 1,484 identical, slug vs id 772 identicalmre
  • 7538b034mission 011 (ticket #25 web part): short page URLs /<slug> and /<slug>/<number>; /projects/<slug>, /projects/<slug>/<n>, /projects/<slug>/tickets/<n> and /tickets/<ref> answer 301 (current slug); slug pages moved behind hl:web's own routes after construction (they answered /__hl/* and /components/*.hl); reserved slugs refused; API paths unchanged. gate 293/0, connect 60/0, live-data copy 187/0, API old vs new: only page links differmre
  • 0369106emission 010 (code order) 4/4: README file map + import order + 'Same output' test, STATUS (entry, lessons, how to verify), LOG, report; tests/realdata-baseline.mjs + realdata-compare*.py (a cleanup answers the same on live data), tests/letcount.pymre
  • a75e0279mission 010 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (456 lets → plain declarations; Hybriel refuses a plain declaration inside a loop on its 2nd pass). gate 249/0, connect 60/0, real-data reads identical, a 50-step write sequence (API + faces) identical to the old codemre
  • e9d5c618mission 010 (code order) 2/4: one lib/ file per topic — store.hl split into projects / tickets (+ relations) / events / tickets-helpers, util.hl shared helpers (env, storage dir, URLs, sorts, Vienna time), the function routes out of project.hl into lib/api.hl (thin; auth/filters/Accept in api-helpers.hl), invite + member-removal logic out of the faces/routes into invites.hl / tickets.hl; project.hl is the map. /login/callback gets req + the session store by reference. gate 249/0, connect 60/0, real-data reads identicalmre
  • 97e269b5mission 010 (code order) 1/4: .hl files out of the root — lib/ (store, users, connections, invites, migrate, markdown, mdview, import = ticketfile, util = localtime, jsoncheck, api-helpers = api), tools/import.hl, components/styles.hl; import paths only. gate 249/0, connect 60/0, real-data reads identicalmre
  • 38f9d10ftickets: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gate 249/0, connect 60/0mre
  • d3db6139tickets: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 249/0, connect 60/0mre
  • bce182e3tickets: Hybriel master 7eea0d32 (#126 memory, #48 lambda copies its argument); migrate.hl lambdas take &logmre
  • 4137be0fantcolony#40: mission references point to the moved missionsmre
  • 9bfba36aantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • c7bd2645tickets: Hybriel master 73267707 (#122 fixed); compactNow workaround removed (#110 covered)mre
  • 2ab91ee9tickets: gate checks rows appear once (session sync); re-vendor to ff51cf46 stopped on hybriel#122, stays 837fe120mre
  • e01c2b1dtickets#24: installable app (manifest, service worker, offline list), own icon; gate waits for the hello's pongmre
  • 752fbb7fdeploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • 38bdd5e4deploy.sh: never send .git or .gitignore to Byrodinmre
  • f12fa1bcState of 2026-09-27, before the move to gitoriamre