tickets
All repositories: gitoria
25.7 KB
// tests/events.mjs — ticket #26: THE EVENT STREAM FOR PROGRAMS (GET /api/events, Server-Sent Events, lib/stream.hl).// Its own server on its own store (tests/events-seed.hl: alice, bob, carol with tokens; projects alpha (alice admin,// bob use) and beta (bob admin); a project key for beta), subscribers that read the stream like curl does (raw HTTP,// no EventSource), a REAL headless Chrome in which alice comments and changes the state by clicks and key presses, a// Hybriel subscriber (tests/events-client.hl, hl:fetch stream mode) and a Python one (urllib). Checked:// 401 without / with a bad token; 400 bad filters; 403 a key outside its project; the stream's headers;// a browser comment and state change arrive within 1 s; every kind (created, comment, state, assign, edit, link);// filters project (one, several, by id), assignee, notMine; a project key sees only its project;// reconnect with Last-Event-ID / ?after= delivers the missed events exactly once; an idle stream lives 2 minutes// (hl:http1's ":" keep-alive comments) and still gets the next event.// node tests/events.mjs (TICKETS_EVENTS_PORT, default 8790; Chrome debug ports TICKETS_EVENTS_CHROME, default// 8793-8799; EVENTS_IDLE_SECONDS, default 125; EVENTS_VIA, a proxy for the subscribers).// Store + log in .scratch/events-store.import { spawn, spawnSync } from 'node:child_process';import http from 'node:http';import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';import { createHash, randomBytes } from 'node:crypto';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { launchBrowser } from './cdp.mjs';if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');const BIN = join(APP, 'bin/hybriel');const PORT = Number(process.env.TICKETS_EVENTS_PORT || 8790);const BASE = `http://127.0.0.1:${PORT}`;const STORE = join(APP, '.scratch/events-store');const IDLE_MS = Number(process.env.EVENTS_IDLE_SECONDS || 125) * 1000;// EVENTS_VIA=<url>: the subscribers connect THROUGH this proxy (e.g. an nginx with the Byrodin vhost's location block// in front of this server); writes and the browser stay directconst VIA = process.env.EVENTS_VIA || BASE;const CHROME = (process.env.TICKETS_EVENTS_CHROME || '8793-8799').split('-').map(Number);const J = JSON.stringify;const sleep = (ms) => new Promise(r => setTimeout(r, ms));// a re-vendored Hybriel compiles each entry at its first start (cold ~20 s on Loreana, hybriel#148; then ~1 s from// ~/.hybriel/cache/run): every start of a .hl program waits up to COLD_MS (TICKETS_COLD_MS, default 120 s)const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);let passes = 0, failures = 0;function check(label, ok, detail = '') {console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);if (ok) passes++; else failures++;}// ---- the store, the server ------------------------------------------------------------------------------------rmSync(STORE, { recursive: true, force: true });mkdirSync(join(STORE, 'mpackdb'), { recursive: true });mkdirSync(join(STORE, 'sessions'), { recursive: true });const seedOut = spawnSync(BIN, ['tests/events-seed.hl'], { cwd: APP, env: { ...process.env, TICKETS_STORAGE: join(STORE, 'mpackdb') }, encoding: 'utf8', timeout: COLD_MS });const seedLine = ((seedOut.stdout || '') + (seedOut.stderr || '')).split('\n').find(l => l.startsWith('SEED '));if (!seedLine) { console.log('the seed failed:\n' + seedOut.stdout + seedOut.stderr); process.exit(1); }const K = JSON.parse(seedLine.slice(5));// alice's browser session: a session file the server revives (the realdata baseline does the same)const sid = randomBytes(16).toString('hex');writeFileSync(join(STORE, 'sessions', createHash('sha256').update(sid).digest('hex')),J({ created: Date.now(), data: { tag: 'eventsgate' }, handled: [], id: sid, seen: Date.now(), user: { id: K.alice } }), { mode: 0o600 });let log = '';const server = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TICKETS_PORT: String(PORT),TICKETS_STORAGE: join(STORE, 'mpackdb'), TICKETS_SESSIONS: join(STORE, 'sessions'), TICKETS_WATCH: '0', TICKETS_PUBLIC_URL: BASE,IDENT_URL: 'http://127.0.0.1:9', IDENT_EXCHANGE_URL: 'http://127.0.0.1:9', IDENT_API_KEY: 'pk_events', IDENT_API_SECRET: '', TICKETS_CREATOR_IDENTITY: '' } });server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);const children = [];// ---- a subscriber, read like curl -N reads it: raw HTTP, the frames parsed here -------------------------------function subscribe(query, token, headers = {}) {const s = { events: [], comments: 0, status: 0, headers: {}, body: '', raw: '', open: true, maxGap: 0, last: 0, started: Date.now() };s.ready = new Promise((ok) => {const h = { ...headers };if (token) h.authorization = 'Bearer ' + token;s.req = http.get(VIA + '/api/events' + query, { headers: h, agent: false }, (res) => {s.status = res.statusCode; s.headers = res.headers; res.setEncoding('utf8');res.on('data', (d) => {const now = Date.now();if (s.last) s.maxGap = Math.max(s.maxGap, now - s.last);s.last = now;if (s.status !== 200) { s.body += d; return; }s.raw += d;let at;while ((at = s.raw.indexOf('\n\n')) >= 0) {const block = s.raw.slice(0, at); s.raw = s.raw.slice(at + 2);const lines = block.split('\n');if (lines.every(l => l.startsWith(':'))) { s.comments++; continue; }const data = lines.filter(l => l.startsWith('data: ')).map(l => l.slice(6)).join('\n');const idl = lines.find(l => l.startsWith('id: '));let json = null; try { json = JSON.parse(data); } catch {}s.events.push({ id: idl ? Number(idl.slice(4)) : null, json, at: now });}ok();});res.on('end', () => { s.open = false; ok(); });res.on('close', () => { s.open = false; ok(); });});s.req.on('error', () => { s.open = false; ok(); });});s.close = () => { s.req.destroy(); s.open = false; };s.kinds = () => s.events.map(e => e.json && e.json.kind);s.waitFor = async (pred, ms = 3000) => { const end = Date.now() + ms; while (Date.now() < end) { const e = s.events.find(pred); if (e) return e; await sleep(20); } return null; };return s;}const api = async (method, path, body, token) => {const r = await fetch(BASE + path, { method, headers: { 'content-type': 'application/json', ...(token ? { authorization: 'Bearer ' + token } : {}) }, body: body ? J(body) : undefined });let json = null; try { json = await r.json(); } catch {}return { status: r.status, json };};const refusal = async (query, token, headers = {}) => {const s = subscribe(query, token, headers);await s.ready; await sleep(100); s.close();let json = null; try { json = JSON.parse(s.body); } catch {}return { status: s.status, json, headers: s.headers };};let browser = null;try {// ---- mission 014 (Apollo's subscriber, 2026-10-19): streams opened AS EARLY AS POSSIBLE must get live events ----------// `first`: retried from the moment the process starts (like a subscriber retrying through the restart's 502s) — it is// the very first request the server answers; `second`: opened right after it; the later streams come after the// server answered /api/projects. Then one write: every one of them must get it within 2 s.const tStart = Date.now();let first = null;for (const end = tStart + COLD_MS; Date.now() < end;) {const s = subscribe('', K.aliceToken);await s.ready;if (s.status === 200 && s.open) { first = s; break; }s.close(); await sleep(50);}if (!first) throw new Error(`no early stream within ${COLD_MS} ms`);console.log(` (the first stream connected ${Date.now() - tStart} ms after the start, the server's first request)`);const second = subscribe('', K.aliceToken);await second.ready;let up = false;for (const end = Date.now() + COLD_MS; !up && Date.now() < end;) { try { up = (await fetch(BASE + '/api/projects')).ok; } catch {} if (!up) await sleep(250); }if (!up) throw new Error(`the server did not come up within ${COLD_MS} ms`);const later = subscribe('', K.aliceToken);await later.ready;await sleep(300);{const t0 = Date.now();const w = await api('POST', '/api/projects/alpha/tickets/1/comments', { text: 'early bird' }, K.aliceToken);check('mission 014: a comment right after the start → 201', w.status === 201, J(w));for (const [name, s] of [['the very first request (retried from process start)', first], ['opened right after it', second], ['opened after the server answered', later]]) {const e = await s.waitFor(e => e.json && e.json.text === 'early bird', 2500);check(`mission 014: the stream ${name} gets the live comment within 2 s`, !!e && e.at - t0 <= 2000 && s.open, e ? (e.at - t0) + ' ms' : 'nothing arrived (open ' + s.open + ', ' + s.comments + ' keep-alives, events ' + J(s.events) + ')');}for (const s of [first, second, later]) s.close();}// ---- refusals -------------------------------------------------------------------------------------------let r = await refusal('', null);check('401 without a token (+ WWW-Authenticate: Bearer)', r.status === 401 && r.headers['www-authenticate'] === 'Bearer' && /event stream needs Authorization/.test(r.json && r.json.error), J(r));r = await refusal('', 'tkt_' + '0'.repeat(48));check('401 with an unknown token', r.status === 401, J(r));r = await refusal('', K.aliceToken.slice(0, -2) + 'zz');check('401 with a malformed token', r.status === 401, J(r));if (VIA !== BASE) console.log(' (subscribers connect through ' + VIA + ')');const post = await fetch(VIA + '/api/events', { method: 'POST', headers: { authorization: 'Bearer ' + K.aliceToken } });check('405 for a POST', post.status === 405, String(post.status));r = await refusal('?after=abc', K.aliceToken);check('400 for after=abc (field after)', r.status === 400 && r.json.field === 'after', J(r));r = await refusal('', K.aliceToken, { 'last-event-id': '-1' });check('400 for Last-Event-ID: -1', r.status === 400 && r.json.field === 'after', J(r));r = await refusal('?project=nope', K.aliceToken);check('400 for an unknown project (field project)', r.status === 400 && r.json.field === 'project' && /nope/.test(r.json.error), J(r));r = await refusal('?assignee=nobody-here', K.aliceToken);check('400 for an unknown assignee', r.status === 400 && r.json.field === 'assignee', J(r));r = await refusal('?project=alpha', K.betaKey);check('403 for a project key asking for another project', r.status === 403 && r.json.field === 'project', J(r));r = await refusal('?notMine=1', K.betaKey);check('400 for notMine with a project key (it writes for many people)', r.status === 400 && r.json.field === 'notMine', J(r));// ---- the subscribers ---------------------------------------------------------------------------------------const idle = subscribe('?project=beta&assignee=carol', K.carolToken); // nothing will match for 2 minutesconst all = subscribe('', K.aliceToken);const alphaBob = subscribe('?project=alpha', K.bobToken);const key = subscribe('', K.betaKey);const notMine = subscribe('?notMine=1', K.aliceToken);const forBob = subscribe('?assignee=bob', K.carolToken);const both = subscribe(`?project=${K.alpha},beta`, K.carolToken);const resumer = subscribe('?project=alpha', K.carolToken);await Promise.all([idle, all, alphaBob, key, notMine, forBob, both, resumer].map(s => s.ready));check('the stream: 200, text/event-stream, no-cache, X-Accel-Buffering: no, held open', all.status === 200 && /^text\/event-stream/.test(all.headers['content-type']) && all.headers['cache-control'] === 'no-cache' && (VIA !== BASE || all.headers['x-accel-buffering'] === 'no') && all.open, J(all.headers));check('a fresh stream (no after) replays nothing', all.events.length === 0, J(all.events));// ---- a REAL browser: alice comments on alpha #1 and changes its state ----------------------------------------browser = await launchBrowser({ debugPortRange: CHROME });const page = await browser.newPage();await page.send('Network.enable');await page.send('Network.setCookie', { name: 'hlsid', value: sid, url: BASE, httpOnly: true });await page.goto(BASE + '/alpha/1');await page.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1 && !!document.querySelector("#commentform md-editor")', { label: 'alpha #1 hydrated, alice signed in', timeout: 20000 });await page.evaluate(`new Promise((ok) => { const s = window.__hl.socket; const h = (ev) => { let f = null; try { f = JSON.parse(ev.data); } catch {} if (f && f.t === 'pong') { s.removeEventListener('message', h); ok(true); } }; s.addEventListener('message', h); s.send(JSON.stringify({ t: 'ping' })); setTimeout(() => ok(false), 10000); })`);// click INTO the visual editor (in the md-editor's shadow root) and type key by keyconst box = await page.evaluate(`(() => { const ed = document.querySelector('#commentform md-editor').shadowRoot.querySelector('[part=editor]'); const b = ed.getBoundingClientRect(); return { x: b.x + b.width / 2, y: b.y + b.height / 2 }; })()`);for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) await page.send('Input.dispatchMouseEvent', { type, x: box.x, y: box.y, button: 'left', clickCount: 1 });const words = 'a comment typed in Chrome';for (const ch of words) {await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });}const typed = await page.evaluate('document.querySelector("#commenttext").value');check('browser: the comment was typed into the editor (the textarea holds it)', typed === words, J(typed));let t0 = Date.now();await page.click('#commentsend');let ev = await all.waitFor(e => e.json && e.json.kind === 'comment' && e.json.text === words, 3000);check('browser comment → the stream within 1 s', ev && ev.at - t0 < 1000, ev ? (ev.at - t0) + ' ms' : 'nothing arrived: ' + J(all.events));if (ev) console.log(` (${ev.at - t0} ms after the click)`);check('the comment event: id, at, project, ticket, ref, number, kind, actor, state, text, href', ev && Number.isInteger(ev.json.id) && ev.id === ev.json.id && /^\d{4}-\d\d-\d\dT/.test(ev.json.at) && ev.json.project === 'alpha' && ev.json.ticket === K.alphaTicket && ev.json.ref === '#1' && ev.json.number === 1 && ev.json.actor === 'alice' && ev.json.state === 'open' && ev.json.href === BASE + '/alpha/1', ev && J(ev.json));await page.waitFor('[...document.querySelectorAll("#events li")].some(li => li.textContent.includes("a comment typed in Chrome"))', { label: 'the comment shows on the page' });await page.evaluate(`(() => { const i = document.querySelector('#newstate'); i.value = 'progress'; i.dispatchEvent(new Event('change', { bubbles: true })); })()`);t0 = Date.now();await page.click('#statesend');ev = await all.waitFor(e => e.json && e.json.kind === 'state', 3000);check('browser state change → the stream within 1 s, state = the new one', ev && ev.at - t0 < 1000 && ev.json.state === 'progress' && ev.json.actor === 'alice', ev ? (ev.at - t0) + ' ms ' + J(ev.json) : 'nothing: ' + J(all.events));if (ev) console.log(` (${ev.at - t0} ms after the click)`);// ---- the API writes: every kind ---------------------------------------------------------------------------const resumeFrom = (await resumer.waitFor(e => e.json && e.json.kind === 'state', 2000) || {}).id;resumer.close(); // carol's program drops off herecheck('bob (use) comments on beta #1 through the API → 201', (await api('POST', '/api/projects/beta/tickets/1/comments', { text: 'bob on beta' }, K.bobToken)).status === 201);check('alice assigns alpha #1 to bob → 201', (await api('POST', '/api/projects/alpha/tickets/1/assign', { assignee: 'bob' }, K.aliceToken)).status === 201);check('bob comments on alpha #1 → 201', (await api('POST', '/api/projects/alpha/tickets/1/comments', { text: 'bob on alpha' }, K.bobToken)).status === 201);check('alice edits alpha #1 → 201', (await api('POST', '/api/projects/alpha/tickets/1/edit', { summary: 'the summary, edited' }, K.aliceToken)).status === 201);const made = await api('POST', '/api/projects/alpha/tickets', { subject: 'alpha two', summary: 'x'.repeat(400) }, K.aliceToken);check('alice opens alpha #2 → 201', made.status === 201, J(made));check('alice marks alpha #2 blocked by beta #1 → 201', (await api('POST', '/api/projects/alpha/tickets/2/blocked-by', { add: 'beta#1' }, K.aliceToken)).status === 201);check('bob moves beta #1 to done → 201', (await api('POST', '/api/projects/beta/tickets/1/state', { state: 'done' }, K.bobToken)).status === 201);await all.waitFor(e => e.json && e.json.kind === 'state' && e.json.project === 'beta', 2000);await sleep(300);const want = ['comment', 'state', 'comment', 'assign', 'comment', 'edit', 'created', 'link', 'state'];check('alice (no filter) got every event in order: ' + want.join(' '), J(all.kinds()) === J(want), J(all.kinds()));const ids = all.events.map(e => e.id);check('event ids increase by one, no gaps, no doubles', ids.every((v, i) => i === 0 || v === ids[i - 1] + 1), J(ids));const byKind = (s, k, p) => s.events.find(e => e.json.kind === k && (!p || e.json.project === p));const cr = byKind(all, 'created');check('created: the summary, cut to 300 characters', cr && cr.json.text === 'x'.repeat(300) && cr.json.number === 2, cr && J(cr.json).slice(0, 200));const ed = byKind(all, 'edit');check('edit: the new summary', ed && ed.json.text === 'the summary, edited', ed && J(ed.json));const as = byKind(all, 'assign');check('assign: assignee bob, text says so', as && as.json.assignee === 'bob' && /assigned the ticket to bob/.test(as.json.text), as && J(as.json));const lk = byKind(all, 'link');check('link: on alpha #2, "marked it blocked by beta #1"', lk && lk.json.number === 2 && /blocked by beta #1/.test(lk.json.text), lk && J(lk.json));const done = all.events.find(e => e.json.kind === 'state' && e.json.project === 'beta');check('state: beta #1 → done', done && done.json.state === 'done' && done.json.actor === 'bob', done && J(done.json));// ---- filters ------------------------------------------------------------------------------------------------const projOf = (s) => [...new Set(s.events.map(e => e.json.project))].sort();check('project=alpha (bob): only alpha events (7)', J(projOf(alphaBob)) === J(['alpha']) && alphaBob.events.length === 7, J(alphaBob.kinds()));check('project=<alpha id>,beta: both projects, all 9', J(projOf(both)) === J(['alpha', 'beta']) && both.events.length === 9, J(both.kinds()));check('project key of beta: only beta events (2), none of alpha', J(projOf(key)) === J(['beta']) && key.events.length === 2, J(key.events.map(e => e.json.project)));check('notMine (alice): only bob\'s events (comment, comment, state)', notMine.events.every(e => e.json.actor === 'bob') && J(notMine.kinds()) === J(['comment', 'comment', 'state']), J(notMine.events.map(e => [e.json.kind, e.json.actor])));check('assignee=bob: from the assign on (assign, comment, edit) — nothing of beta', J(forBob.kinds()) === J(['assign', 'comment', 'edit']) && forBob.events.every(e => e.json.project === 'alpha'), J(forBob.kinds()));// ---- resume: carol's program missed what happened after the state change -------------------------------const missed = all.events.filter(e => e.id > resumeFrom && e.json.project === 'alpha').map(e => e.id);const back = subscribe('?project=alpha', K.carolToken, { 'last-event-id': String(resumeFrom) });await back.ready;await back.waitFor(e => e.id === missed[missed.length - 1], 2000);await sleep(200);check(`reconnect with Last-Event-ID: ${resumeFrom} → exactly the ${missed.length} missed alpha events, in order`, J(back.events.map(e => e.id)) === J(missed), J(back.events.map(e => e.id)) + ' want ' + J(missed));const viaQuery = subscribe(`?project=alpha&after=${resumeFrom}`, K.carolToken);await viaQuery.ready; await viaQuery.waitFor(e => e.id === missed[missed.length - 1], 2000); await sleep(200);check('the same with ?after=', J(viaQuery.events.map(e => e.id)) === J(missed), J(viaQuery.events.map(e => e.id)));const header = subscribe(`?project=alpha&after=1`, K.carolToken, { 'last-event-id': String(resumeFrom) });await header.ready; await sleep(400);check('Last-Event-ID wins over ?after=', J(header.events.map(e => e.id)) === J(missed), J(header.events.map(e => e.id)));viaQuery.close(); header.close();check('then a new write arrives live, once', (await api('POST', '/api/projects/alpha/tickets/2/comments', { text: 'after the resume' }, K.aliceToken)).status === 201);const live = await back.waitFor(e => e.json.text === 'after the resume', 2000);await sleep(300);check('… on the resumed stream exactly once, the next id', live && back.events.filter(e => e.json.text === 'after the resume').length === 1 && live.id === all.events[all.events.length - 1].id, J(back.events.map(e => e.id)));const fromZero = subscribe('?after=0', K.aliceToken);await fromZero.ready; await sleep(500);const total = all.events[all.events.length - 1].id;check(`?after=0 replays every numbered event 1…${total} (the seed's two tickets too), no doubles`, J(fromZero.events.map(e => e.id)) === J([...Array(total).keys()].map(i => i + 1)), J(fromZero.events.map(e => e.id)));fromZero.close(); back.close();// ---- other clients: Hybriel (hl:fetch stream mode) and Python (urllib) ------------------------------------------const hlc = spawn(BIN, ['tests/events-client.hl'], { cwd: APP, env: { ...process.env, EVENTS_URL: VIA + '/api/events?project=beta&after=0', EVENTS_TOKEN: K.bobToken, EVENTS_MAX: '3' } });children.push(hlc);let hlOut = ''; hlc.stdout.on('data', d => hlOut += d); hlc.stderr.on('data', d => hlOut += d);let hlClosed = false; hlc.on('close', () => { hlClosed = true; }); // 'close' = exited AND its output readconst py = spawn('python3', ['-I', '-c', `import urllib.request, json, sysreq = urllib.request.Request(sys.argv[1] + '/api/events?project=beta', headers={'Authorization': 'Bearer ' + sys.argv[2]})with urllib.request.urlopen(req, timeout=20) as r:print('STATUS', r.status, flush=True)for raw in r:line = raw.decode().rstrip('\\n')if line.startswith('data: '):print('EVENT', line[6:], flush=True)break`, VIA, K.bobToken]);children.push(py);let pyOut = ''; py.stdout.on('data', d => pyOut += d); py.stderr.on('data', d => pyOut += d);for (let i = 0; i < 40 && !/STATUS 200/.test(pyOut); i++) await sleep(100);check('beta: bob comments for the Python client → 201', (await api('POST', '/api/projects/beta/tickets/1/comments', { text: 'for python' }, K.bobToken)).status === 201);for (let i = 0; i < 60 && !/EVENT/.test(pyOut); i++) await sleep(100);// the Hybriel client compiles at its first start (cold ~20 s, hybriel#148); it replays from after=0, so waiting is safefor (const end = Date.now() + COLD_MS; !/DONE/.test(hlOut) && !hlClosed && Date.now() < end;) await sleep(100);const pyEv = (pyOut.split('\n').find(l => l.startsWith('EVENT ')) || '').slice(6);check('Python (urllib) reads the live event', /"text":"for python"/.test(pyEv), pyOut);const hlEvs = hlOut.split('\n').filter(l => l.startsWith('EVENT ')).map(l => JSON.parse(l.slice(6)));check('Hybriel (hl:fetch stream = true) reads 3 beta events from after=0 and stops', hlEvs.length === 3 && hlEvs.every(e => e.project === 'beta') && hlEvs[0].kind === 'created', J(hlEvs.map(e => [e.id, e.project, e.kind])) + ' ' + hlOut.split('\n').filter(l => !l.startsWith('EVENT ')).join(' | ').slice(0, 600));// ---- the idle stream: 2 minutes without a matching event --------------------------------------------------await page.close().catch(() => {});const left = IDLE_MS - (Date.now() - idle.started);if (left > 0) { console.log(` (waiting ${Math.round(left / 1000)} s more for the idle stream)`); await sleep(left); }check(`idle stream: open after ${Math.round((Date.now() - idle.started) / 1000)} s, nothing delivered, keep-alive comments every ≤ 7 s (${idle.comments} comments, largest gap ${idle.maxGap} ms)`, idle.open && idle.events.length === 0 && idle.comments >= Math.floor(IDLE_MS / 7000) && idle.maxGap <= 7000, J({ open: idle.open, n: idle.events.length, c: idle.comments, gap: idle.maxGap }));check('bob makes carol a member of beta (200) and assigns beta #1 to her (201)', (await api('POST', '/api/projects/beta/members', { user: 'carol', role: 'use' }, K.bobToken)).status === 200 && (await api('POST', '/api/projects/beta/tickets/1/assign', { assignee: 'carol' }, K.bobToken)).status === 201);const late = await idle.waitFor(e => e.json.kind === 'assign', 2000);check('… and the 2-minute idle stream still delivers it', !!late && late.json.assignee === 'carol', J(idle.events));for (const s of [idle, all, alphaBob, key, notMine, forBob, both]) s.close();} catch (e) {check('the test ran to its end', false, e.stack + '\n' + log.slice(-2000));} finally {for (const c of children) { try { c.kill('SIGKILL'); } catch {} }if (browser) await browser.close().catch(() => {});server.kill('SIGTERM');await sleep(500);try { process.kill(server.pid, 'SIGKILL'); } catch {}writeFileSync(join(STORE, 'server.log'), log);}const errors = log.split('\n').filter(l => /error/i.test(l) && !/error absorbed/.test(l));check('the server log has no errors', errors.length === 0, errors.slice(0, 5).join(' | '));console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);
Branches
Latest commits
- eb7aeeb9mission brief 016mre
- e4c34759paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
- 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