tickets
All repositories: gitoria
8.6 KB
// lib/stream.hl — THE EVENT STREAM FOR PROGRAMS (ticket #26): every change of a ticket, live, as Server-Sent Events.// Statics only, the server realm. `GET /api/events` (lib/api.hl getEvents) checks the token and calls openStream.//// streamTable pk *n (the table's counter: 1, 2, 3, … — THE EVENT ID a program resumes from)// { event (events @id), ticket (tickets @id), project (projects @id), number, kind, actor (users @id// or ''), actorName, state (the ticket's state after the write), assignee (users @id, ''),// previous (an 'assign' event: who had it, ''), text (≤ 300 characters), created (epoch ms) }// One row per history event, written by tickets.hl (recordEvent) right after the write is complete,// so `state` / `assignee` are the ticket's NEW ones. Rows exist from the first write after ticket #26// went live; older history is not numbered (a program reads it from GET /api/projects/<p>/tickets/<n>).//// THE WIRE (text/event-stream, hl:http1's native SSE: `sseStart` on the request's respond handle,// `sseSend` per frame; hl:http1 writes ": connected" first and a ":" comment every 5 s — the keep-alive):// data: {"id":42,"at":"…","project":"routger","ticket":"…","ref":"#5","number":5,"kind":"comment",// "actor":"Apollo","state":"open","assignee":"","text":"…","href":"https://…/routger/5"}// id: 42// A reconnect with `Last-Event-ID: 42` (EventSource does it itself) or `?after=42` first gets every row after 42// that passes the filters, oldest first, then the live ones — nothing twice, nothing missed (one event loop: no// write can slip between the replay and the registration).//// WHO SEES WHAT: reading tickets is public (CONCEPT.md point 1), so a user's token sees every project; a project// key (tktc_, ticket #21) only its own project. Filters (query): project (slugs or ids, comma separated),// assignee (a name, a users id, or `me`), notMine (skip what the token's user wrote; a user token only).import { timestamp } from 'hl:time'import { sseStart, sseSend, sseAlive } from 'hl:http1'import { MPackDB } from 'hl:mpackdb'import { storageDir, countOf, clean, isDigits, ticketHref } from './util.hl'import { publicUrl } from './users.hl'import { projectRecord, projectByRef, userByRef } from './projects.hl'import { eventRecord, eventRowOf } from './events.hl'static streamTable = new MPackDB(file = storageDir + '/stream.db', primaryKey = '*n', indexes = [])static textMax = 300// THE TRANSPORT: hl:http1's native SSE, imported by name (hybriel#144): sseStart turns a request into a stream (a// connection id, or null), sseSend writes one frame (true / false = that stream is gone), sseAlive asks without// sending. hl:http1 writes ": connected" first and a ":" comment every 5 s (the keep-alive) and reaps a closed peer at// once. Plain HTTP only (on hl:http1's own TLS sseStart answers null; on Byrodin TLS ends in nginx). The pages' browser// build binds these to a refusal that throws only when called — and the browser never calls them.// the live subscribers: { conn (hl:http1 SSE connection id), projects (ids or null = all), assignee, notMine }static subscribers = []// ---- writing: one row per history event ---------------------------------------------------------// `t` = the ticket record AFTER the write. Answers the new event id (n), or null.static recordEvent = (eventId, t) => {if (eventId == null || t == null) { return null }e = eventRecord(eventId)if (e == null) { return null }row = eventRowOf(e, t)let text = row.textif (e.kind == 'created') { text = t.summary != null && t.summary != '' ? t.summary : row.text }if (e.kind == 'edit') { text = e.summary != null ? e.summary : '' }if (e.kind == 'link' || e.kind == 'assign') { text = row.label }short = text.length > textMax ? text.slice(0, textMax) : textn = 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 })if (n == null) {console.log('stream: could not number event ' + eventId + ': ' + streamTable.lastError())return null}publish(streamTable.fetch(n))return n}// ---- the payload a program gets ----------------------------------------------------------------------static payloadOf = (r) => {p = projectRecord(r.project)slug = p != null ? p.slug : ''who = r.assignee != '' ? userByRef(r.assignee, null) : nullreturn { 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) }}// one SSE message: the data line, then its id line (hl:http1 writes "data: " before and the blank line after)static frameOf = (r) => { return JSON.stringify(payloadOf(r)) + newline + 'id: ' + r.n }// the language has no escapes: a newline is written as itselfstatic newline = ""// ---- filters --------------------------------------------------------------------------------------static passes = (sub, r) => {if (sub.projects != null && !sub.projects.includes(r.project)) { return false }if (sub.assignee != null && r.assignee != sub.assignee && r.previous != sub.assignee) { return false }if (sub.notMine != null && r.actor == sub.notMine) { return false }return true}// the query of GET /api/events → { sub } or { error, field, forbidden? }.// `who` = { user } (a user's token) or { project } (a project key: that project only); `lastId` = the// Last-Event-ID header or null.static subscriptionOf = (q, lastId, who) => {let projects = nullif (who.project != null) { projects = [who.project] }want = clean(q.project)if (want != '') {ids = []for (part of want.split(',')) {let ref = part.trim()if (ref != '') {let p = projectByRef(ref)if (p == null) { return { error = 'no such project: ' + ref field = 'project' } }if (who.project != null && p.id != who.project) { return { error = 'this key reaches only its own project, not ' + ref field = 'project' forbidden = true } }ids.push(p.id)}}if (ids.length > 0) { projects = ids }}let assignee = nulla = clean(q.assignee)if (a != '') {if (a == 'me') {if (who.user == null) { return { error = 'assignee=me needs a user token' field = 'assignee' } }assignee = who.user.id} else {f = userByRef(a, null)if (f.error != null) { return { error = f.error field = 'assignee' } }assignee = f.user.id}}let notMine = nullnm = clean(q.notMine).toLowerCase()if (nm != '' && nm != '0' && nm != 'false' && nm != 'no') {if (who.user == null) { return { error = 'notMine needs a user token (a project key writes for many people)' field = 'notMine' } }notMine = who.user.id}let after = nullsince = clean(lastId) != '' ? clean(lastId) : clean(q.after)if (since != '') {if (!isDigits(since)) { return { error = 'after / Last-Event-ID must be an event id (digits)' field = 'after' } }after = toNumber(since)}return { sub = { projects = projects assignee = assignee notMine = notMine after = after } }}// ---- the stream ------------------------------------------------------------------------------------// turns the request into the event stream (`respond` = req.respond), sends what was missed since// `sub.after`, then registers it for the live ones. Answers the SSE connection id, or null.static openStream = (respond, sub) => {conn = sseStart(respond)if (conn == null) { return null }if (sub.after != null) {let n = sub.after + 1last = streamTable.count()while (n <= last) {let r = streamTable.fetch(n)if (r != null && passes(sub, r)) { sseSend(conn, frameOf(r)) }n = n + 1}}subscribers.push({ conn = conn projects = sub.projects assignee = sub.assignee notMine = sub.notMine })return conn}// a new row to every live subscriber whose filters it passes; a closed stream drops out herestatic publish = (r) => {if (r == null || subscribers.length == 0) { return 0 }let sent = 0let gone = falseframe = frameOf(r)for (s of subscribers) {if (passes(s, r)) {if (sseSend(s.conn, frame)) { sent = sent + 1 } else { gone = true }} else if (!sseAlive(s.conn)) { gone = true }}if (gone) { prune() }return sent}static prune = () => {keep = []for (s of subscribers) { if (sseAlive(s.conn)) { keep.push(s) } }while (subscribers.length > 0) { subscribers.pop() }for (s of keep) { subscribers.push(s) }}
Branches
Latest commits
- 26efb23freport w6-events (events test)mre
- c6bfab04mission 015: re-vendor Hybriel 0f396652 (static build), reportmre
- b7ec5981mission brief 015mre
- 5dc68731docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
- 8a460b16mission 014: Apollo's 'stream opened right after the start gets no live events' is not a tickets bug — events.mjs checks early streamsmre
- 6309ca81mission brief 014mre
- c1161469mission 013: GitHub pipe tables on ticket pages (lib/markdown.hl + View + CSS) and re-vendor hybriel master a832f73bmre
- a30b5d12mission brief (w13)mre
- b50a6f93w9 (tickets): re-vendor hybriel 9f912f3b (#146 emit in a lib static, #147) — the 12 live-push emits in lib/api.hl compile as they are; cold start (#148): tests wait TICKETS_COLD_MS for every start, deploy.sh gates browser + events and waits up to 120 s for the URL, container /tmp tmpfs + hybriel-cache volume; events-client stops at EVENTS_MAX inside a chunk; connect.mjs ports by env. bin/hybriel sha256 7421907868ac07d8a7d08296b083c6f8b20407d0e099ce4bebbf7ae053d9060a. Gates (8720–8739): browser 315/0 (+ all-cold 315/0), events 48/0 cold, connect 60/0, short-id 19/0; real-data copy old 0e8a41c vs new: 2,425 reads + 72 writes identical after masking ?v hashes, offline at, route order; event stream on the copy delivers. Not deployed.mre
- 43be6578w9: re-vendor hybriel master edfd400a; event stream imports sseStart/sseSend/sseAlive from hl:http1 (hybriel#144), useTransport gone; tools/import.hl plain declarations. BLOCKED: hybriel-native refuses `emit client` in a static (lib/api.hl) — the server does not compile on edfd400a, gates fail at start; scratch copy without those emits: events 48/0, gate 254 ok up to the first live pushmre
- 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