gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit1b37d4041b37d404RV39 on hold: hybriel#308mre1b37d404/plugins/web/sessions.hl

17.2 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 store pass walks the store
  10. // to REMOVE expired files, never to revive, and never all at once: a slice of a few
  11. // milliseconds per request (W179: a walk of 392 000 files stalled the one request thread 15-30 s).
  12. //
  13. // THE FILENAME IS A HASH OF THE ID, NEVER THE ID: a value a client sent must not
  14. // become a path, and `ls` on the store must not hand out live ids.
  15. //
  16. // THREE CLOCKS, all seconds: `maxAge` is how long a session stays VALID after its
  17. // last touch (the cookie's Max-Age too); `idle` how long it stays RESIDENT in
  18. // memory with no live socket (eviction is non-destructive — the file is the
  19. // truth — so a short clock is safe); `sweepEvery` how often the sweep may run,
  20. // piggybacking on real requests (no timer: a site with no requests has nothing
  21. // to sweep). `stampDrift` bounds how far the on-disk `seen` may lag the one in
  22. // memory, so an active session does not cost a disk write per asset request.
  23. //
  24. // `dir` is the store's absolute path, or null for memory only (the app's
  25. // `sessionDir = false`). The default the framework hands in is `<project>/.sessions`
  26. // — a DOT directory, which the dev watcher skips by construction (measured in the
  27. // archive: a store inside the watched tree made every session write a re-analysis).
  28. import HlwSession from './session.hl'
  29. import { randomToken } from 'hl:http1'
  30. import { now } from 'hl:time'
  31. import { sha256 } from 'hl:crypto'
  32. import { readFile, listDir, exists, writeFile, mkDir, remove, changeTime, stat } from 'hl:fs'
  33. String dir = null
  34. Number maxAge = 1209600
  35. Number idle = 900
  36. Number sweepEvery = 300
  37. Number stampDrift = 60
  38. String cookie = 'hlsid'
  39. secure = null // null: `Secure` when the request came over https; true: always; false: never
  40. Number anonMax = 10000 // the most anonymous sessions (nobody logged in) kept; the oldest go first (W124)
  41. String domain = '' // the cookie's `Domain` (ticket #44): '' = this host only
  42. Number anonKeep = 86400 // seconds an anonymous session with no data keeps its file; the store pass removes older ones (W179)
  43. Number slice = 40 // milliseconds of one request the store pass may use (W179)
  44. map = {} // id → Session, the resident ones
  45. persistedSeen = {} // id → the `seen` last written to disk (write avoidance only)
  46. stamped = {} // id → the file's change time when THIS process last read or wrote it (ident#28)
  47. lastSweep = 0
  48. anonOrder = [] // ids of the anonymous sessions, oldest first (W124 eviction backstop)
  49. reported = {} // path → true: a foreign file in the store, said once
  50. queue = null // the store pass in progress: the listing of the directory, read a slice per request (W179)
  51. qi = 0 // the next entry of `queue`
  52. qGone = 0 // files this pass removed so far
  53. lastPass = 0 // when the last pass began
  54. // ---- the store --------------------------------------------------------------------
  55. path(sid) {
  56. if (dir == null) { return null }
  57. return dir + '/' + sha256(sid)
  58. }
  59. open() {
  60. if (dir != null) { mkDir(dir, 448) }
  61. lastSweep = now()
  62. if (startPass()) { storeSlice() } // the first pass begins at boot (one listing, one slice); a foreign file in a small store is named at once
  63. return null
  64. }
  65. load(sid) {
  66. let p = path(sid)
  67. if (p == null || !exists(p)) { return null }
  68. let stamp = changeTime(p) // taken BEFORE the read: a write that lands between them shows at the next lookup
  69. let raw = readFile(p)
  70. if (raw == null || !isSessionText(raw)) { return null }
  71. let rec = JSON.parse(raw)
  72. if (rec == null || rec.id != sid) { return null }
  73. let s = rec > new HlwSession()
  74. map[sid] = s
  75. persistedSeen[sid] = s.seen
  76. stamped[sid] = stamp
  77. return s
  78. }
  79. // IDENT#28 — THE FILE IS THE TRUTH, MEMORY ONLY A COPY. Another process on the same store (the standby
  80. // beside the main one) can write a login into the file while this process holds the session resident.
  81. // `refresh` compares the file's change time with the one this process last saw and, when the file is
  82. // newer, copies it INTO the resident session (the same object, so every socket holding the handle sees
  83. // it). Answers true when it reloaded. A missing or foreign file leaves memory alone.
  84. refresh(s) {
  85. if (dir == null || s == null || s.id == null) { return false }
  86. let p = path(s.id)
  87. let stamp = changeTime(p)
  88. if (stamp == null || stamp == stamped[s.id]) { return false }
  89. let raw = readFile(p)
  90. if (raw == null || !isSessionText(raw)) { return false }
  91. let rec = JSON.parse(raw)
  92. if (rec == null || rec.id != s.id) { return false }
  93. let f = rec > new HlwSession()
  94. s.user = f.user
  95. s.data = f.data
  96. s.handled = f.handled
  97. s.created = f.created
  98. s.issuedSig = f.issuedSig
  99. s.issuedAt = f.issuedAt
  100. if (f.seen > s.seen) { s.seen = f.seen }
  101. persistedSeen[s.id] = f.seen
  102. stamped[s.id] = stamp
  103. return true
  104. }
  105. put(s) {
  106. let p = path(s.id)
  107. if (p == null) { return null }
  108. if (!exists(dir)) { mkDir(dir, 448) }
  109. // IDENT#28: never put an older memory copy over a newer file that holds a login this one lacks
  110. if (s.user == null && stamped[s.id] != null && changeTime(p) != stamped[s.id]) {
  111. refresh(s)
  112. if (s.user != null) { return null }
  113. }
  114. writeFile(p, JSON.stringify(s), 384)
  115. persistedSeen[s.id] = s.seen
  116. stamped[s.id] = changeTime(p)
  117. return null
  118. }
  119. drop(sid) {
  120. let p = path(sid)
  121. if (p != null) { remove(p) }
  122. persistedSeen[sid] = null
  123. stamped[sid] = null
  124. return null
  125. }
  126. // ---- the cookie ----------------------------------------------------------------
  127. parseCookies(header) {
  128. let out = {}
  129. if (header == null) { return out }
  130. for (part of header.split(';')) {
  131. let eq = part.indexOf('=')
  132. if (eq > 0) { out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim() }
  133. }
  134. return out
  135. }
  136. // `https` is whether THIS request came over https (TLS on the server, or X-Forwarded-Proto); the app's
  137. // `sessionSecure` overrides it either way (W124)
  138. cookieHeader(sid, https) {
  139. let sec = secure == null ? https == true : secure
  140. // W138: remember when and with which attributes this session's cookie went out (see `due`)
  141. let rec = sid != null ? map[sid] : null
  142. if (rec != null) {
  143. rec.issuedSig = signature(sec)
  144. rec.issuedAt = now()
  145. save(rec)
  146. }
  147. return cookie + '=' + sid + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + maxAge + (domain != '' ? '; Domain=' + domain : '') + (sec ? '; Secure' : '')
  148. }
  149. // W138 (gitoria#24, creator rule): a short signature of the cookie's attributes
  150. signature(sec) {
  151. return cookie + '|' + domain + '|/|' + (sec ? 'S' : '-') + '|Lax'
  152. }
  153. // W138: does a session's cookie need to go out again? Yes when it was never issued, was issued
  154. // with other attributes (a Domain added since), or was
  155. // last issued more than a day ago (Chrome caps a cookie's lifetime at 400 days, and logins do not expire).
  156. // Anonymous sessions that carry a cookie count too (ident#28: a cookie issued with an old short Max-Age is replaced within a day of its next request); a request
  157. // with no cookie has no session here and gets none (lazy sessions).
  158. due(s, https) {
  159. if (s == null || s.id == null) { return false }
  160. let sec = secure == null ? https == true : secure
  161. return s.issuedSig != signature(sec) || now() - s.issuedAt >= 86400000
  162. }
  163. // ---- the map ---------------------------------------------------------------------
  164. // the session a cookie header names: resident, or revived from its file; null when
  165. // it names none (no cookie, or an id nobody knows — that browser is anonymous)
  166. resolve(cookieHeader) {
  167. let ids = cookieValues(cookieHeader)
  168. if (ids.length == 0) { return null }
  169. if (ids.length == 1) { return byId(ids[0]) }
  170. // W137 (gitoria#24): a browser can hold two cookies of the session's name (an old host-only one and a
  171. // newer one with the Domain) and sends both. The first that belongs to a signed-in session wins, else
  172. // the first that belongs to any known session, else none.
  173. let first = null
  174. for (id of ids) {
  175. let s = lookup(id)
  176. if (s == null) { continue }
  177. if (s.user != null) { first = s break }
  178. if (first == null) { first = s }
  179. }
  180. if (first == null) { return null }
  181. touch(first)
  182. return first
  183. }
  184. // every value the Cookie header carries under the session's name, in the order sent
  185. cookieValues(header) {
  186. let out = []
  187. if (header == null) { return out }
  188. for (part of header.split(';')) {
  189. let eq = part.indexOf('=')
  190. if (eq > 0 && part.slice(0, eq).trim() == cookie) { out.push(part.slice(eq + 1).trim()) }
  191. }
  192. return out
  193. }
  194. // W137: the extra headers an answer carries when the request held the session's name more than once and
  195. // `s` is the session chosen among them: the chosen id again with the app's cookie attributes (Domain
  196. // included) under 'Set-Cookie', and, only when the app's cookie has a Domain, a host-only expiry under
  197. // 'set-cookie' (a second header line: the server writes one line per key, and the two keys differ in
  198. // case only). Without a Domain the expiry would delete the chosen cookie itself.
  199. repair(cookieHeaderText, s, https) {
  200. let out = {}
  201. if (s == null || s.id == null) { return out }
  202. let many = cookieValues(cookieHeaderText).length > 1
  203. if (!many && !due(s, https)) { return out }
  204. out['Set-Cookie'] = cookieHeader(s.id, https)
  205. if (many && domain != '') { out['set-cookie'] = expiry(https) }
  206. return out
  207. }
  208. // the same name, no Domain, gone at once: removes a stray host-only cookie
  209. expiry(https) {
  210. let sec = secure == null ? https == true : secure
  211. return cookie + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0' + (sec ? '; Secure' : '')
  212. }
  213. // for /__hl/adopt, which sets a new id and chooses nothing: the host-only strays are expired so the new
  214. // cookie is the only one of its name
  215. strays(cookieHeaderText, https) {
  216. let out = {}
  217. if (domain != '' && cookieValues(cookieHeaderText).length > 1) { out['set-cookie'] = expiry(https) }
  218. return out
  219. }
  220. byId(sid) {
  221. let s = lookup(sid)
  222. if (s == null) { return null }
  223. touch(s)
  224. return s
  225. }
  226. lookup(sid) {
  227. if (sid == null) { return null }
  228. let s = map[sid]
  229. if (s == null) { s = load(sid) } else { refresh(s) }
  230. return s
  231. }
  232. // SESSIONS ARE LAZY (W124): a visitor with no cookie has NO session — `fresh()` hands a transient
  233. // one (no id, not in the map, nothing on disk) that a page renders with or a face writes to. Only a
  234. // session that GOT something (a login, `data`, an upload) is `adopt`ed: it gets its id, goes into the
  235. // map and onto disk, and the caller sets the cookie. A flood of cookie-less requests so costs nothing,
  236. // and the anonymous ones that were adopted are capped (`anonMax`, oldest first).
  237. fresh() {
  238. return new HlwSession(created = now(), seen = now())
  239. }
  240. // A NEW SESSION WITH AN ID, in the map and on disk (the call W124 removed and apps used): `adopt(fresh())`.
  241. // The caller sets the cookie (`cookieHeader(s.id)`).
  242. mint() {
  243. return adopt(fresh())
  244. }
  245. // does the session hold anything worth a cookie and a file?
  246. hasContent(s) {
  247. return s != null && (s.user != null || s.data.keys().length > 0)
  248. }
  249. adopt(s) {
  250. maybeSweep([])
  251. if (s.id == null) { s.id = randomToken(32) }
  252. map[s.id] = s
  253. put(s)
  254. if (s.user == null) {
  255. anonOrder.push(s.id)
  256. if (anonOrder.length > anonMax) { evictAnon() }
  257. }
  258. return s
  259. }
  260. // ROTATE (W120): the session `s` gets a NEW id — its user, data and handled list move with it
  261. // (it is the same record, only the id changes), the old id's file and memory entry are deleted so a
  262. // planted id is anonymous from now on. Answers the old id. The caller tells the browser (cookie).
  263. move(s) {
  264. let old = s.id
  265. let sid = randomToken(32)
  266. map[old] = null
  267. drop(old)
  268. s.id = sid
  269. s.rotating = false
  270. s.seen = now()
  271. map[sid] = s
  272. put(s)
  273. let i = anonOrder.indexOf(old)
  274. if (i >= 0) { anonOrder[i] = sid }
  275. return old
  276. }
  277. // an upload (no content yet) is adopted at once; a face's session only when hasContent()
  278. evictAnon() {
  279. let over = anonOrder.length - anonMax
  280. let keep = []
  281. let n = 0
  282. for (id of anonOrder) {
  283. let s = map[id]
  284. if (s == null || s.user != null) { continue }
  285. if (n < over) {
  286. drop(id)
  287. map[id] = null
  288. n = n + 1
  289. } else {
  290. keep.push(id)
  291. }
  292. }
  293. anonOrder = keep
  294. return null
  295. }
  296. // ONE WRITE PATH for the stamp: every request or frame that presents a session
  297. // moves `seen`; the file follows only when it has drifted `stampDrift` seconds
  298. touch(s) {
  299. refresh(s)
  300. s.seen = now()
  301. if (dir != null && s.id != null) {
  302. let last = persistedSeen[s.id]
  303. if (last == null || s.seen - last >= stampDrift * 1000) { put(s) }
  304. }
  305. return null
  306. }
  307. // what a face wrote (login, a cart) reaches the file now, not at the next drift
  308. save(s) {
  309. if (s != null && s.id != null && map[s.id] != null) { put(s) }
  310. return null
  311. }
  312. // ---- the sweep -------------------------------------------------------------------
  313. // `live` is the set of session ids with an open socket — those are never evicted
  314. maybeSweep(live) {
  315. let listed = false
  316. if (now() - lastSweep >= sweepEvery * 1000) { listed = sweep(live) }
  317. if (queue != null && !listed) { storeSlice() } // the request that listed the directory does no slice too
  318. return null
  319. }
  320. sweep(live) {
  321. lastSweep = now()
  322. let cutoff = now() - maxAge * 1000
  323. let cold = now() - idle * 1000
  324. let evicted = 0
  325. let expired = 0
  326. let next = {}
  327. for (k of map.keys()) {
  328. let s = map[k]
  329. if (s == null) {
  330. // dropped earlier
  331. } else if (s.seen <= cutoff && !(refresh(s) && s.seen > cutoff)) {
  332. drop(k)
  333. expired = expired + 1
  334. } else if (dir != null && s.seen <= cold && !live.includes(k)) {
  335. persistedSeen[k] = null
  336. evicted = evicted + 1
  337. } else {
  338. next[k] = s
  339. }
  340. }
  341. map = next // a fresh hybrid: the compaction (archive, mission 261)
  342. if (evicted + expired > 0) {
  343. console.log('sessions: sweep — evicted ' + evicted + ', expired ' + expired + ', ' + map.keys().length + ' resident')
  344. }
  345. // a new pass over the files on disk starts when none runs and the last began long enough ago
  346. if (dir != null && queue == null && exists(dir) && now() - lastPass >= sweepEvery * 12000) { return startPass() }
  347. return false
  348. }
  349. startPass() {
  350. if (dir == null || queue != null || !exists(dir)) { return false }
  351. lastPass = now()
  352. queue = []
  353. for (e of listDir(dir)) { queue.push(e) } // listDir's answer has no length and no index
  354. qi = 0
  355. qGone = 0
  356. return true
  357. }
  358. // W179: ONE SLICE of the store pass, as many files as fit in `slice` milliseconds, then the request goes on.
  359. // A file whose change time is newer than the shortest clock is skipped without being read. Of the others:
  360. // a session with a user goes only when its `seen` is past `maxAge`; an anonymous one with no data goes when
  361. // older than `anonKeep` (it is what a lazy session would have been: nothing). A resident session is never touched.
  362. storeSlice() {
  363. let t0 = now()
  364. let young = t0 - (anonKeep < maxAge ? anonKeep : maxAge) * 1000
  365. let cutoff = t0 - maxAge * 1000
  366. let old = t0 - anonKeep * 1000
  367. let n = queue.length
  368. let done = 0
  369. while (qi < n && (done % 64 != 63 || now() - t0 < slice)) {
  370. let e = queue[qi]
  371. qi = qi + 1
  372. done = done + 1
  373. if (!isSessionName(e.name) || e.type != 'file') {
  374. foreign(e)
  375. } else {
  376. let st = stat(e.path)
  377. let raw = st != null && st.mtime <= young ? readFile(e.path) : null
  378. if (raw != null && isSessionText(raw)) {
  379. let rec = JSON.parse(raw)
  380. let dead = rec.user != null ? rec.seen <= cutoff : (rec.seen <= old && (rec.data == null || rec.data.keys().length == 0))
  381. if (dead && map[rec.id] == null) {
  382. remove(e.path)
  383. persistedSeen[rec.id] = null
  384. qGone = qGone + 1
  385. }
  386. }
  387. }
  388. }
  389. if (qi >= n) {
  390. console.log('sessions: store pass done — ' + n + ' file(s) looked at, ' + qGone + ' removed')
  391. queue = null
  392. }
  393. return null
  394. }
  395. // ---- what the store holds that is not a session -----------------------------------
  396. // A FILE THAT IS NOT A SESSION IS SKIPPED, NEVER PARSED. The store is a directory an
  397. // operator can put anything into (a marker, an editor's backup, a copy), and
  398. // `JSON.parse` aborts the program on text that is not JSON — at the boot sweep that was
  399. // the whole server, before it served anything (ticket #26). Every file this layer
  400. // writes is named by a sha256 (64 lowercase hex characters) and holds a Session's JSON,
  401. // whose keys come out in the order the Session class declares its fields (older stores wrote them sorted, so a file opening with `{"created":` is still a session); a session file is a JSON object that carries the keys `created` and `seen`. `writeFile` renames a
  402. // finished temp file over the target, so a torn session file cannot occur. A file that
  403. // is not that shape is left where it is, and said once.
  404. isSessionName(name) {
  405. if (name.length != 64) { return false }
  406. for (c of name.split('')) {
  407. if (!'0123456789abcdef'.includes(c)) { return false }
  408. }
  409. return true
  410. }
  411. isSessionText(raw) {
  412. let t = raw.trim()
  413. return t.startsWith('{"') && t.endsWith('}') && t.includes('"created":') && t.includes('"seen":')
  414. }
  415. foreign(e) {
  416. if (reported[e.path] == null) {
  417. reported[e.path] = true
  418. 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')
  419. }
  420. return null
  421. }

Branches

Latest commits

  • 1b37d404RV39 on hold: hybriel#308mre
  • f9127c68Revert "Merge branch 'rv39'"mre
  • cd39f3d3log: hybriel#308mre
  • 51341d6elog: RV39 deploy startedmre
  • c9e29e06Merge branch 'rv39'mre
  • 0f8d1fdclog: RV39 report, browser 387/2mre
  • 50249b0bRV39: reportmre
  • 10ed9581compose: HL_GC_STATS=1mre
  • 955da19bRV39: re-vendor Hybriel set day39 (source 51e921d7, bin 6b481aa7)mre
  • 64b8d1dclog: RV39 startedmre
  • 1f2df72amission RV39mre
  • 6c1936f9log+status: GC planmre
  • 2846a840log: m569 result, GC hypothesismre
  • b24cd2d5log: Anton on hl:fetch, mission 569mre
  • 7d42cac1log+status: SL1 measured, fetch stalls remainmre
  • 8e5f2ceflog: SL1 deployedmre
  • 29f34212log: SL1 deploy startedmre
  • 529dd741Merge sl1-slices: slice details repair and person fill (SL1)mre
  • 8a83316blog: SL1 result, session drain slowermre
  • 35e93e8dSL1: slice the details repair and person fill: catalog lists changed in place, 40 ms fill steps, people created in steps, writes one table per tickmre