gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain5d144817Merge branch 'records-t40' into mainTicketsmain/lib/stream.hl

9.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: `sseStart` on the request's respond handle,
  13. // `sseSend` 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 { sseStart, sseSend, sseAlive } from 'hl:http1'
  26. import { MPackDB } from 'hl:mpackdb'
  27. import { storageDir, countOf, clean, isDigits, ticketHref } from './util.hl'
  28. import { publicUrl } from './users.hl'
  29. import { projectRecord, projectByRef, userByRef } from './projects.hl'
  30. import { eventRecord, eventRowOf } from './events.hl'
  31. static streamTable = new MPackDB(file = storageDir + '/stream.db', primaryKey = '*n', indexes = [])
  32. static textMax = 300
  33. // THE TRANSPORT: hl:http1's native SSE, imported by name (hybriel#144): sseStart turns a request into a stream (a
  34. // connection id, or null), sseSend writes one frame (true / false = that stream is gone), sseAlive asks without
  35. // sending. hl:http1 writes ": connected" first and a ":" comment every 5 s (the keep-alive) and reaps a closed peer at
  36. // once. Plain HTTP only (on hl:http1's own TLS sseStart answers null; on Byrodin TLS ends in nginx). The pages' browser
  37. // build binds these to a refusal that throws only when called — and the browser never calls them.
  38. // the live subscribers: { conn (hl:http1 SSE connection id), projects (ids or null = all), assignee, notMine }
  39. static subscribers = []
  40. // One additive callback for ticket #51; it never awaits network I/O.
  41. static streamListeners = []
  42. static hearStream = (fn) => { streamListeners.push(fn) }
  43. // ---- writing: one row per history event ---------------------------------------------------------
  44. // `t` = the ticket record AFTER the write. Answers the new event id (n), or null.
  45. static recordEvent = (eventId, t) => {
  46. if (eventId == null || t == null) { return null }
  47. e = eventRecord(eventId)
  48. if (e == null) { return null }
  49. row = eventRowOf(e, t)
  50. let text = row.text
  51. if (e.kind == 'created') { text = t.summary != null && t.summary != '' ? t.summary : row.text }
  52. if (e.kind == 'edit') { text = e.summary != null ? e.summary : '' }
  53. if (e.kind == 'link' || e.kind == 'assign') { text = row.label }
  54. short = text.length > textMax ? text.slice(0, textMax) : text
  55. 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 })
  56. if (n == null) {
  57. console.log('stream: could not number event ' + eventId + ': ' + streamTable.lastError())
  58. return null
  59. }
  60. written = streamTable.fetch(n)
  61. publish(written)
  62. for (fn of streamListeners) { fn(written) }
  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 (r.kind == 'purged') { return false }
  80. if (sub.projects != null && !sub.projects.includes(r.project)) { return false }
  81. if (sub.assignee != null && r.assignee != sub.assignee && r.previous != sub.assignee) { return false }
  82. if (sub.notMine != null && r.actor == sub.notMine) { return false }
  83. return true
  84. }
  85. // the query of GET /api/events → { sub } or { error, field, forbidden? }.
  86. // `who` = { user } (a user's token) or { project } (a project key: that project only); `lastId` = the
  87. // Last-Event-ID header or null.
  88. static subscriptionOf = (q, lastId, who) => {
  89. let projects = null
  90. if (who.project != null) { projects = [who.project] }
  91. want = clean(q.project)
  92. if (want != '') {
  93. ids = []
  94. for (part of want.split(',')) {
  95. ref = part.trim()
  96. if (ref != '') {
  97. p = projectByRef(ref)
  98. if (p == null) { return { error = 'no such project: ' + ref field = 'project' } }
  99. if (who.project != null && p.id != who.project) { return { error = 'this key reaches only its own project, not ' + ref field = 'project' forbidden = true } }
  100. ids.push(p.id)
  101. }
  102. }
  103. if (ids.length > 0) { projects = ids }
  104. }
  105. let assignee = null
  106. a = clean(q.assignee)
  107. if (a != '') {
  108. if (a == 'me') {
  109. if (who.user == null) { return { error = 'assignee=me needs a user token' field = 'assignee' } }
  110. assignee = who.user.id
  111. } else {
  112. f = userByRef(a, null)
  113. if (f.error != null) { return { error = f.error field = 'assignee' } }
  114. assignee = f.user.id
  115. }
  116. }
  117. let notMine = null
  118. nm = clean(q.notMine).toLowerCase()
  119. if (nm != '' && nm != '0' && nm != 'false' && nm != 'no') {
  120. if (who.user == null) { return { error = 'notMine needs a user token (a project key writes for many people)' field = 'notMine' } }
  121. notMine = who.user.id
  122. }
  123. let after = null
  124. since = clean(lastId) != '' ? clean(lastId) : clean(q.after)
  125. if (since != '') {
  126. if (!isDigits(since)) { return { error = 'after / Last-Event-ID must be an event id (digits)' field = 'after' } }
  127. after = toNumber(since)
  128. }
  129. return { sub = { projects = projects assignee = assignee notMine = notMine after = after } }
  130. }
  131. // ---- the stream ------------------------------------------------------------------------------------
  132. // turns the request into the event stream (`respond` = req.respond), sends what was missed since
  133. // `sub.after`, then registers it for the live ones. Answers the SSE connection id, or null.
  134. static openStream = (respond, sub) => {
  135. conn = sseStart(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. r = streamTable.fetch(n)
  142. if (r != null && passes(sub, r)) { sseSend(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) { 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 (sseSend(s.conn, frame)) { sent = sent + 1 } else { gone = true }
  158. } else if (!sseAlive(s.conn)) { gone = true }
  159. }
  160. if (gone) { prune() }
  161. return sent
  162. }
  163. static prune = () => {
  164. keep = []
  165. for (s of subscribers) { if (sseAlive(s.conn)) { keep.push(s) } }
  166. while (subscribers.length > 0) { subscribers.pop() }
  167. for (s of keep) { subscribers.push(s) }
  168. }
  169. // ---- the one-time purge of #94, identity rule (lib/migrate.hl purgeTicket94) -------------------------------------
  170. // The counter must not move: `count()` is the last number everywhere (replay, subscription cursors). So a row of a purged event
  171. // is NOT deleted: it is rewritten empty under its own number, kind 'purged', and every reader skips it (passes, matchesSubscription).
  172. // `eventIds` = a map event @id → true; `ticketId` = a ticket @id. Answers how many rows were emptied.
  173. static blankRowsOf = (eventIds, ticketId) => {
  174. hit = []
  175. for (r of streamTable.iterate(null, null)) {
  176. if (r.kind != 'purged' && (eventIds[r.event] == true || r.ticket == ticketId)) { hit.push(r.n) }
  177. }
  178. for (n of hit) {
  179. streamTable.update(n, { n = n event = '' ticket = '' project = '' number = 0 kind = 'purged' actor = '' actorName = '' state = '' assignee = '' previous = '' text = '' created = 0 })
  180. }
  181. return hit.length
  182. }
  183. static compactStream = () => { streamTable.compactNow() }

Branches

Latest commits

  • 5d144817Merge branch 'records-t40' into mainTickets
  • 44ee6f06|||PR records: #43 #45 livemre
  • b8fdeee9Merge branch 'p39-routes' into mainTickets
  • a0187a0a|||PR Remove redundant route-order loopmre
  • 369e4b9cMerge branch 'k40-lists' into mainTickets
  • 9af8e780|||PR Use keyed list mutations for live ticket updatesmre
  • 610d8e8aMerge branch 'records-t39' into mainTickets
  • 32bcdf24|||PR records: GO P39 K40mre
  • 4123c6d1Merge branch 'records-t38' into mainTickets
  • cd3641a1|||PR records: day72 deploy live, tickets closedmre
  • 7d44d852Merge branch 'records-t37' into mainTickets
  • 926f7061|||PR records: merges, D36 deploymre
  • bf58534eMerge branch 'l33-final' into mainTickets
  • 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
  • 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
  • 5822cb3aMerge branch 'o34-clean' into mainTickets
  • 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
  • 14cf96b4Merge branch 'records-t36' into mainTickets
  • 07749fa1|||PR records: day72 + #40 mergedmre
  • ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre