tickets
All repositories: gitoria
28.0 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 article")', { 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 (the Comments block's MdEditor, mission 016) and type key by keyconst box = await page.evaluate(`(() => { const ed = document.querySelector('#commentform md-editor article'); ed.scrollIntoView({ block: 'center' }); 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("#commentform md-editor input.value").value');check('browser: the comment was typed into the editor (its field holds it)', typed === words, J(typed));let t0 = Date.now();await page.click('#commentform button.comment-post');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' });// the state change is the composer's State select (real keys: ArrowDown until it shows "progress") and its main button ("Set to progress")await page.evaluate(`document.querySelector('#commentform select[name=state]').focus()`);for (let i = 0; i < 12 && !(await page.evaluate(`(() => { const s = document.querySelector('#commentform select[name=state]'); return s.options[s.selectedIndex].textContent.trim() === 'progress'; })()`)); i++) {await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });await sleep(120);}check('browser: the composer\'s button says "Set to progress" with only the state chosen', (await page.evaluate(`document.querySelector('#commentform button.comment-post').textContent.trim()`)) === 'Set to progress');t0 = Date.now();await page.click('#commentform button.comment-post');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();// Mission 030: a note edit does not replace or relabel the numbered state event.const noteState = await api('POST', '/api/projects/alpha/tickets/1/state', { state: 'done', text: 'original state note' }, K.aliceToken);check('m030: create a state transition with a note', noteState.status === 201 && noteState.json.event.kind === 'state', J(noteState));const noteEdit = await api('POST', '/api/projects/alpha/tickets/1/comments/' + noteState.json.event.id + '/edit', { text: 'edited state note' }, K.aliceToken);check('m030: edit a state note without changing its kind or label', noteEdit.status === 200 && noteEdit.json.event.kind === 'state' && noteEdit.json.event.label === 'changed the state' && noteEdit.json.event.edited === true, J(noteEdit));const noteReplay = subscribe('?project=alpha&after=0', K.aliceToken);try {await noteReplay.ready;const originalState = await noteReplay.waitFor(e => e.json.kind === 'state' && e.json.text === 'original state note', 2000);check('m030: /api/events replays the original state and note; note edits add no event or display label', originalState && originalState.json.state === 'done' && originalState.json.label === undefined && originalState.json.edited === undefined && !noteReplay.events.some(e => e.json.text === 'edited state note'), J(noteReplay.events.map(e => e.json)));} finally { noteReplay.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
- 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