gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita5d45d00a5d45d00records: D38 cause, GOmrea5d45d00/lib/stream.hl

8.8 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 (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. ref = part.trim()
  95. if (ref != '') {
  96. 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. conn = sseStart(respond)
  135. if (conn == null) { return null }
  136. if (sub.after != null) {
  137. let n = sub.after + 1
  138. last = streamTable.count()
  139. while (n <= last) {
  140. r = streamTable.fetch(n)
  141. if (r != null && passes(sub, r)) { sseSend(conn, frameOf(r)) }
  142. n = n + 1
  143. }
  144. }
  145. subscribers.push({ conn = conn projects = sub.projects assignee = sub.assignee notMine = sub.notMine })
  146. return conn
  147. }
  148. // a new row to every live subscriber whose filters it passes; a closed stream drops out here
  149. static publish = (r) => {
  150. if (r == null || subscribers.length == 0) { return 0 }
  151. let sent = 0
  152. let gone = false
  153. frame = frameOf(r)
  154. for (s of subscribers) {
  155. if (passes(s, r)) {
  156. if (sseSend(s.conn, frame)) { sent = sent + 1 } else { gone = true }
  157. } else if (!sseAlive(s.conn)) { gone = true }
  158. }
  159. if (gone) { prune() }
  160. return sent
  161. }
  162. static prune = () => {
  163. keep = []
  164. for (s of subscribers) { if (sseAlive(s.conn)) { keep.push(s) } }
  165. while (subscribers.length > 0) { subscribers.pop() }
  166. for (s of keep) { subscribers.push(s) }
  167. }

Branches

Latest commits

  • a5d45d00records: D38 cause, GOmre
  • 19eeb938records: D38 gates, two day38b failuresmre
  • 94d6ca2arecords: D38 startedmre
  • 9df09aacmission 029: day38b re-vendor + deploymre
  • d2834f65records: #94 backup planmre
  • 4467d8cbrecords: #94 purge readymre
  • 506a4efdmission 028: #94, identity rulemre
  • 78c7f48eRefine mpackdb holdmre
  • 3d7d89c8Record mpackdb hold until day38mre
  • f1bf7195#51 done; my subscription idmre
  • 9870b945status: #51 proof greenmre
  • e92173c6log: #51 live push proofmre
  • 72d87041log: Hermes push livemre
  • 1d69bf7dTickets conductor: park until Hermes pushmre
  • 80d8cfd1Tickets conductor: #51 livemre
  • 61641dd9Complete subscriptions deployment evidencemre
  • c980856cRecord successful subscriptions deployment and live checksmre
  • 4b4710adMerge branch 's51-subscriptions'mre
  • a731ef7eTickets conductor: S51 reviewed, deploy stepmre
  • b487b05aRecord verified direct push protocol handoffmre