gitoria

components

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitee9f1b57ee9f1b57mission brief w6mreee9f1b57/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

  • ee9f1b57mission brief w6mre
  • fe691586components (mission 005) 4/4: docs (README components + gate 290, STATUS, LOG), report reports/005-fixes-16-17-5.mdmre
  • f1ebab53components #5 (mission 005) 3/4: file upload for several files (components/files-upload, demo /files-upload) — pure Hybriel, each file through emit server uploadFile (hybriel#94), drop or choose many, a row per file with live progress, one after the other in order, a drop during an upload waits, a file over uploadMax fails in its row and the next goes, 'n of m uploaded'; home entry, routes, map line, README; pagination keyboard focus ring #555 (Chrome painted its own orange one); docker-compose init: true (hybriel#156); gate 290/0 (17 #5 checks with real file drops, 1 #16 focus check)mre
  • 3b73ae5bcomponents #16 (mission 005) 2/4: Pagination tells the host the target page — the host hands onPage (hybriel#87: a function, not emit), called on every click that changes the page (pointer, Enter/Space, script click; Previous/Next/numbers/first/last; not … or the current page) with the target read from the clicked button's data-page before the rebuild; demo shows what the page was told; README Data out; 15 gate checks (14 fail on the old pagination)mre
  • 6b27c0f0components #17 (mission 005) 1/4: md-editor keeps backslash + r — parseInto dropped the two characters '\r' (C:\root -> C:oot) instead of a real carriage return; CR now decoded from JSON (String.fromCharCode does not parse in a member), real CRs also go from pasted plain text; 5 gate checks (3 fail on the old md-editor.hl)mre
  • 1a5dc327mission brief w5mre
  • a567b579components (mission 004) 3/3: docs (README Hybriel a832f73b + tables, STATUS, LOG), report reports/004-md-editor-tables.mdmre
  • 70fe7ab5components (mission 004) 2/3: GitHub pipe tables in the Hybriel MdEditor (creator notes#5; behaviour of notes md-editor.js 9acc27f, no JavaScript) — parse/render (header, :--/:-:/--: alignment, \| in cells and code, inline Markdown in cells, outer pipes optional), padded writer, unchanged table byte for byte, typing | a | b | Enter |---|---| Enter makes a table, Tab/Shift+Tab, Enter new row, Enter in empty last row leaves, Backspace/Delete never merge, selection across a table empties cells, pasted HTML table -> table, thin #999 lines, wide table scrolls in its box; demo third editor 'plan'; gate 252/0 (22 new table checks, 20 fail on the old md-editor.hl)mre
  • f2adb3f3components (mission 004) 1/3: Hybriel master a832f73b (incremental build cache, HL_CACHE_DIR, #151) — bin/hybriel sha256 e1b53f7ce687f5afbe3db34bcda69958f56e730571e4841923c9c8eb3d272db9 built from git archive a832f73b (HL_NO_PLUGINS=1 native/build.sh), the same nine plugins; container: HL_CACHE_DIR=/cache on volume hybriel-cache, /tmp tmpfs; tests wait COMPONENTS_COLD_MS (120 s) for every start; deploy.sh DEPLOY_URL_WAIT 120 s; gate 230/0 coldmre
  • 91bd8a0dmission brief (w4)mre
  • 3bc905c5components #15 (mission 003) 2/2: docs (README Look, STATUS, LOG), reportmre
  • 5a98d77ecomponents #15 (mission 003) 1/2: black/white base look — greys for nuances, no WorldAPI fallbacks, no decorative frames; site + icon black/white; gate 230/0mre
  • 3f93d716components code order (mission 002) 4/4: docs, tests/letcount.py, tests/same-output*, reportmre
  • e747cfa0components code order (mission 002) 3/4: let only where reassigned (257 dropped, 0 never-reassigned left); gate 220/0, layouts gate 73/0, same outputmre
  • 172914a3components code order (mission 002) 2/4: lib/uploads.hl (demo upload storage), thin demo handlers, project.hl map; gate 220/0, same outputmre
  • d29f35b1components code order (mission 002) 1/4: styles.hl -> components/styles.hl; gate 220/0, same outputmre
  • 09945750components: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, http1 773de63e); gate 220/0mre
  • ede4d19acomponents: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 220/0mre
  • 2bb9a935components: Hybriel master 8efba065 (re-vendor round 069: #126 memory, #48 lambda copy)mre
  • e4f01768antcolony#40: mission references point to the moved missionsmre