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(',')) {ref = part.trim()if (ref != '') {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) {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
- b03f11b6Tickets conductor: CONDUCTOR.md (project part), short STATUS.md, old STATUS to archive/2026-10-31mre
- a4123831tickets#42: the /connect and /login/callback error pages are app pages: the function routes redirect to /connect/failed/<code> and /login/failed/<code> (components/problem.hl, sentences in lib/problems.hl), htmlPage and its hand-written stylesheet are gone; gate tests/error-pages.mjsmre
- cefc7b4atickets: a startup error prints its message before exit 1 (hybriel#247)mre
- 99bd6570tickets: lib/migrate.hl writes no table of another topic any more: projects.hl rewriteSlug / addProjectNamed / hasMembers, tickets.hl moveToProject / ticketRecords / ticketRecordsOf, events.hl renameStates / eventRecords / eventRecordsOf; the migration calls them (tickets#47)mre
- b57161e3tickets: the markup names its own rules (Style.pMessage, Style.olTickets, ...) instead of hand-written class strings that copy a stylesheet rule; the shared bodies sit in lib/looks.hl (tickets#38)mre
- f767b24dtickets: 111 needless let became plain declarations (3 in ticket.hl, ticket_list.hl, comments.hl and 108 never-reassigned, not captured loop-body ones); the 212 really reassigned lets stay (tickets#44)mre
- 16c0d3b5tickets: the modal window is phone first: the full-screen sheet is the base rule, the centred window sits in the min-width 60rem block (tickets#39)mre
- 090ee809tickets: every component's styles in its own nested Style {} block; styles.hl keeps only the theme inherit, the accent and the site-wide rules (tickets#36)mre
- d395763ftickets: ident-access gate ports 8769/8768 (8797 is taken on loreana)mre
- afb9a403tickets: an ident access key (Authorization: Bearer idt_…) works in the API (ident#27 app side): lib/ident-access.hl copied from components, read keys GET only, ident down 503; gate tests/ident-access-tickets.mjsmre
- 48c1ba79tickets: md-paste-files gate with the file manager casesmre
- f04afc43tickets: MdEditor from components 59704ce (a file manager copy still attaches, pipe rows, tickets#49)mre
- 06599fa0tickets: MdEditor from components b0f1ec2 (a clipboard with text always pastes the text, tickets#49); real Ctrl+V gatemre
- 2e1b116ftickets: re-vendor Hybriel master acaceaf3 (framework ec8d6c1d): plugins/web patch queue while a page is built, anonymous session cookies refresh; gate waits for the comment editors to draw (W174) and clicks the form editor when it stands still; security gate: main's code runs on its own binary, lazy-session cookie checksmre
- 361bc0fetickets: re-vendor Hybriel 7a684920 (WIP, not deployed); on Error exits 1 at startup; migrate passes its log by reference; gate checks follow lazy sessions and the 413 refusalmre
- 8a69999cident#28: /login/callback never signs out the session it finds; a valid code puts the user on the same sessionmre
- 337e9b21tickets#37: a comment's files are open to everyone who can read the commentmre
- 1800600ftickets: write the standby service out in full so the boot gate can read the main servicemre
- 8179d287tickets: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
- 0398145ctickets: the table grid rule is marked functional for check-thememre