gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit0e8a41ca0e8a41caw6 (ticket #26): event stream for programs — GET /api/events (Server-Sent Events)mre0e8a41ca/lib/stream.hl

8.9 KB

  1. // lib/stream.hl — THE EVENT STREAM FOR PROGRAMS (ticket #26): every change of a ticket, live, as Server-Sent Events.
  2. // Statics only, the server realm. `GET /api/events` (lib/api.hl getEvents) checks the token and calls openStream.
  3. //
  4. // streamTable pk *n (the table's counter: 1, 2, 3, … — THE EVENT ID a program resumes from)
  5. // { event (events @id), ticket (tickets @id), project (projects @id), number, kind, actor (users @id
  6. // or ''), actorName, state (the ticket's state after the write), assignee (users @id, ''),
  7. // previous (an 'assign' event: who had it, ''), text (≤ 300 characters), created (epoch ms) }
  8. // One row per history event, written by tickets.hl (recordEvent) right after the write is complete,
  9. // so `state` / `assignee` are the ticket's NEW ones. Rows exist from the first write after ticket #26
  10. // went live; older history is not numbered (a program reads it from GET /api/projects/<p>/tickets/<n>).
  11. //
  12. // THE WIRE (text/event-stream, hl:http1's native SSE through lib/sse.hl: `sse_start` on the request's respond handle,
  13. // `sse_send` per frame; hl:http1 writes ": connected" first and a ":" comment every 5 s — the keep-alive):
  14. // data: {"id":42,"at":"…","project":"routger","ticket":"…","ref":"#5","number":5,"kind":"comment",
  15. // "actor":"Apollo","state":"open","assignee":"","text":"…","href":"https://…/routger/5"}
  16. // id: 42
  17. // A reconnect with `Last-Event-ID: 42` (EventSource does it itself) or `?after=42` first gets every row after 42
  18. // that passes the filters, oldest first, then the live ones — nothing twice, nothing missed (one event loop: no
  19. // write can slip between the replay and the registration).
  20. //
  21. // WHO SEES WHAT: reading tickets is public (CONCEPT.md point 1), so a user's token sees every project; a project
  22. // key (tktc_, ticket #21) only its own project. Filters (query): project (slugs or ids, comma separated),
  23. // assignee (a name, a users id, or `me`), notMine (skip what the token's user wrote; a user token only).
  24. import { timestamp } from 'hl:time'
  25. import { MPackDB } from 'hl:mpackdb'
  26. import { storageDir, countOf, clean, isDigits, ticketHref } from './util.hl'
  27. import { publicUrl } from './users.hl'
  28. import { projectRecord, projectByRef, userByRef } from './projects.hl'
  29. import { eventRecord, eventRowOf } from './events.hl'
  30. static streamTable = new MPackDB(file = storageDir + '/stream.db', primaryKey = '*n', indexes = [])
  31. static textMax = 300
  32. // THE TRANSPORT: hl:http1's native SSE (http1.zig: `sse_start` on a request's respond handle, a registry of open
  33. // streams, a ":" comment every 5 s as the keep-alive, a closed peer reaped at once). hl:http1 has no .hl wrapper for
  34. // sending yet, a static cannot reach `__native`, and the browser build of the pages (they import tickets.hl → here)
  35. // cannot compile it — so project.hl's root hands the three calls in at the start (useTransport). Plain HTTP only
  36. // (hl:http1 refuses sse_start on its own TLS; on Byrodin TLS ends in nginx).
  37. static sse = { start = null send = null alive = null }
  38. static useTransport = (start, send, alive) => {
  39. sse.start = start
  40. sse.send = send
  41. sse.alive = alive
  42. }
  43. // the live subscribers: { conn (hl:http1 SSE connection id), projects (ids or null = all), assignee, notMine }
  44. static subscribers = []
  45. // ---- writing: one row per history event ---------------------------------------------------------
  46. // `t` = the ticket record AFTER the write. Answers the new event id (n), or null.
  47. static recordEvent = (eventId, t) => {
  48. if (eventId == null || t == null) { return null }
  49. e = eventRecord(eventId)
  50. if (e == null) { return null }
  51. row = eventRowOf(e, t)
  52. let text = row.text
  53. if (e.kind == 'created') { text = t.summary != null && t.summary != '' ? t.summary : row.text }
  54. if (e.kind == 'edit') { text = e.summary != null ? e.summary : '' }
  55. if (e.kind == 'link' || e.kind == 'assign') { text = row.label }
  56. short = text.length > textMax ? text.slice(0, textMax) : text
  57. n = streamTable.put({ event = e.id ticket = t.id project = t.project number = t.number kind = e.kind actor = e.user != null ? e.user : '' actorName = row.author state = t.state assignee = t.assignee != null ? t.assignee : '' previous = e.kind == 'assign' && e.previous != null ? e.previous : '' text = short created = e.created })
  58. if (n == null) {
  59. console.log('stream: could not number event ' + eventId + ': ' + streamTable.lastError())
  60. return null
  61. }
  62. publish(streamTable.fetch(n))
  63. return n
  64. }
  65. // ---- the payload a program gets ----------------------------------------------------------------------
  66. static payloadOf = (r) => {
  67. p = projectRecord(r.project)
  68. slug = p != null ? p.slug : ''
  69. who = r.assignee != '' ? userByRef(r.assignee, null) : null
  70. return { id = r.n at = timestamp(r.created) project = slug ticket = r.ticket ref = '#' + r.number number = r.number kind = r.kind actor = r.actorName state = r.state assignee = who != null && who.user != null ? who.user.name : '' text = r.text href = publicUrl + ticketHref(slug, r.number) }
  71. }
  72. // one SSE message: the data line, then its id line (hl:http1 writes "data: " before and the blank line after)
  73. static frameOf = (r) => { return JSON.stringify(payloadOf(r)) + newline + 'id: ' + r.n }
  74. // the language has no escapes: a newline is written as itself
  75. static newline = "
  76. "
  77. // ---- filters --------------------------------------------------------------------------------------
  78. static passes = (sub, r) => {
  79. if (sub.projects != null && !sub.projects.includes(r.project)) { return false }
  80. if (sub.assignee != null && r.assignee != sub.assignee && r.previous != sub.assignee) { return false }
  81. if (sub.notMine != null && r.actor == sub.notMine) { return false }
  82. return true
  83. }
  84. // the query of GET /api/events → { sub } or { error, field, forbidden? }.
  85. // `who` = { user } (a user's token) or { project } (a project key: that project only); `lastId` = the
  86. // Last-Event-ID header or null.
  87. static subscriptionOf = (q, lastId, who) => {
  88. let projects = null
  89. if (who.project != null) { projects = [who.project] }
  90. want = clean(q.project)
  91. if (want != '') {
  92. ids = []
  93. for (part of want.split(',')) {
  94. let ref = part.trim()
  95. if (ref != '') {
  96. let p = projectByRef(ref)
  97. if (p == null) { return { error = 'no such project: ' + ref field = 'project' } }
  98. if (who.project != null && p.id != who.project) { return { error = 'this key reaches only its own project, not ' + ref field = 'project' forbidden = true } }
  99. ids.push(p.id)
  100. }
  101. }
  102. if (ids.length > 0) { projects = ids }
  103. }
  104. let assignee = null
  105. a = clean(q.assignee)
  106. if (a != '') {
  107. if (a == 'me') {
  108. if (who.user == null) { return { error = 'assignee=me needs a user token' field = 'assignee' } }
  109. assignee = who.user.id
  110. } else {
  111. f = userByRef(a, null)
  112. if (f.error != null) { return { error = f.error field = 'assignee' } }
  113. assignee = f.user.id
  114. }
  115. }
  116. let notMine = null
  117. nm = clean(q.notMine).toLowerCase()
  118. if (nm != '' && nm != '0' && nm != 'false' && nm != 'no') {
  119. if (who.user == null) { return { error = 'notMine needs a user token (a project key writes for many people)' field = 'notMine' } }
  120. notMine = who.user.id
  121. }
  122. let after = null
  123. since = clean(lastId) != '' ? clean(lastId) : clean(q.after)
  124. if (since != '') {
  125. if (!isDigits(since)) { return { error = 'after / Last-Event-ID must be an event id (digits)' field = 'after' } }
  126. after = toNumber(since)
  127. }
  128. return { sub = { projects = projects assignee = assignee notMine = notMine after = after } }
  129. }
  130. // ---- the stream ------------------------------------------------------------------------------------
  131. // turns the request into the event stream (`respond` = req.respond), sends what was missed since
  132. // `sub.after`, then registers it for the live ones. Answers the SSE connection id, or null.
  133. static openStream = (respond, sub) => {
  134. if (sse.start == null) { return null }
  135. conn = sse.start(respond)
  136. if (conn == null) { return null }
  137. if (sub.after != null) {
  138. let n = sub.after + 1
  139. last = streamTable.count()
  140. while (n <= last) {
  141. let r = streamTable.fetch(n)
  142. if (r != null && passes(sub, r)) { sse.send(conn, frameOf(r)) }
  143. n = n + 1
  144. }
  145. }
  146. subscribers.push({ conn = conn projects = sub.projects assignee = sub.assignee notMine = sub.notMine })
  147. return conn
  148. }
  149. // a new row to every live subscriber whose filters it passes; a closed stream drops out here
  150. static publish = (r) => {
  151. if (r == null || subscribers.length == 0 || sse.send == null) { return 0 }
  152. let sent = 0
  153. let gone = false
  154. frame = frameOf(r)
  155. for (s of subscribers) {
  156. if (passes(s, r)) {
  157. if (sse.send(s.conn, frame) == 1) { sent = sent + 1 } else { gone = true }
  158. } else if (sse.alive(s.conn) != 1) { gone = true }
  159. }
  160. if (gone) { prune() }
  161. return sent
  162. }
  163. static prune = () => {
  164. if (sse.alive == null) { return 0 }
  165. keep = []
  166. for (s of subscribers) { if (sse.alive(s.conn) == 1) { keep.push(s) } }
  167. while (subscribers.length > 0) { subscribers.pop() }
  168. for (s of keep) { subscribers.push(s) }
  169. }

Branches

Latest commits

  • 0e8a41caw6 (ticket #26): event stream for programs — GET /api/events (Server-Sent Events)mre
  • 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