gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain5d144817Merge branch 'records-t40' into mainTicketsmain/tests/events.mjs

28.0 KB

  1. // tests/events.mjs — ticket #26: THE EVENT STREAM FOR PROGRAMS (GET /api/events, Server-Sent Events, lib/stream.hl).
  2. // Its own server on its own store (tests/events-seed.hl: alice, bob, carol with tokens; projects alpha (alice admin,
  3. // bob use) and beta (bob admin); a project key for beta), subscribers that read the stream like curl does (raw HTTP,
  4. // no EventSource), a REAL headless Chrome in which alice comments and changes the state by clicks and key presses, a
  5. // Hybriel subscriber (tests/events-client.hl, hl:fetch stream mode) and a Python one (urllib). Checked:
  6. // 401 without / with a bad token; 400 bad filters; 403 a key outside its project; the stream's headers;
  7. // a browser comment and state change arrive within 1 s; every kind (created, comment, state, assign, edit, link);
  8. // filters project (one, several, by id), assignee, notMine; a project key sees only its project;
  9. // reconnect with Last-Event-ID / ?after= delivers the missed events exactly once; an idle stream lives 2 minutes
  10. // (hl:http1's ":" keep-alive comments) and still gets the next event.
  11. // node tests/events.mjs (TICKETS_EVENTS_PORT, default 8790; Chrome debug ports TICKETS_EVENTS_CHROME, default
  12. // 8793-8799; EVENTS_IDLE_SECONDS, default 125; EVENTS_VIA, a proxy for the subscribers).
  13. // Store + log in .scratch/events-store.
  14. import { spawn, spawnSync } from 'node:child_process';
  15. import http from 'node:http';
  16. import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';
  17. import { createHash, randomBytes } from 'node:crypto';
  18. import { dirname, join, resolve } from 'node:path';
  19. import { fileURLToPath } from 'node:url';
  20. import { launchBrowser } from './cdp.mjs';
  21. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  22. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  23. const BIN = join(APP, 'bin/hybriel');
  24. const PORT = Number(process.env.TICKETS_EVENTS_PORT || 8790);
  25. const BASE = `http://127.0.0.1:${PORT}`;
  26. const STORE = join(APP, '.scratch/events-store');
  27. const IDLE_MS = Number(process.env.EVENTS_IDLE_SECONDS || 125) * 1000;
  28. // EVENTS_VIA=<url>: the subscribers connect THROUGH this proxy (e.g. an nginx with the Byrodin vhost's location block
  29. // in front of this server); writes and the browser stay direct
  30. const VIA = process.env.EVENTS_VIA || BASE;
  31. const CHROME = (process.env.TICKETS_EVENTS_CHROME || '8793-8799').split('-').map(Number);
  32. const J = JSON.stringify;
  33. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  34. // a re-vendored Hybriel compiles each entry at its first start (cold ~20 s on Loreana, hybriel#148; then ~1 s from
  35. // ~/.hybriel/cache/run): every start of a .hl program waits up to COLD_MS (TICKETS_COLD_MS, default 120 s)
  36. const COLD_MS = Number(process.env.TICKETS_COLD_MS || 120000);
  37. let passes = 0, failures = 0;
  38. function check(label, ok, detail = '') {
  39. console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`);
  40. if (ok) passes++; else failures++;
  41. }
  42. // ---- the store, the server ------------------------------------------------------------------------------------
  43. rmSync(STORE, { recursive: true, force: true });
  44. mkdirSync(join(STORE, 'mpackdb'), { recursive: true });
  45. mkdirSync(join(STORE, 'sessions'), { recursive: true });
  46. const seedOut = spawnSync(BIN, ['tests/events-seed.hl'], { cwd: APP, env: { ...process.env, TICKETS_STORAGE: join(STORE, 'mpackdb') }, encoding: 'utf8', timeout: COLD_MS });
  47. const seedLine = ((seedOut.stdout || '') + (seedOut.stderr || '')).split('\n').find(l => l.startsWith('SEED '));
  48. if (!seedLine) { console.log('the seed failed:\n' + seedOut.stdout + seedOut.stderr); process.exit(1); }
  49. const K = JSON.parse(seedLine.slice(5));
  50. // alice's browser session: a session file the server revives (the realdata baseline does the same)
  51. const sid = randomBytes(16).toString('hex');
  52. writeFileSync(join(STORE, 'sessions', createHash('sha256').update(sid).digest('hex')),
  53. J({ created: Date.now(), data: { tag: 'eventsgate' }, handled: [], id: sid, seen: Date.now(), user: { id: K.alice } }), { mode: 0o600 });
  54. let log = '';
  55. const server = spawn(BIN, ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, TICKETS_PORT: String(PORT),
  56. TICKETS_STORAGE: join(STORE, 'mpackdb'), TICKETS_SESSIONS: join(STORE, 'sessions'), TICKETS_WATCH: '0', TICKETS_PUBLIC_URL: BASE,
  57. 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: '' } });
  58. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  59. const children = [];
  60. // ---- a subscriber, read like curl -N reads it: raw HTTP, the frames parsed here -------------------------------
  61. function subscribe(query, token, headers = {}) {
  62. const s = { events: [], comments: 0, status: 0, headers: {}, body: '', raw: '', open: true, maxGap: 0, last: 0, started: Date.now() };
  63. s.ready = new Promise((ok) => {
  64. const h = { ...headers };
  65. if (token) h.authorization = 'Bearer ' + token;
  66. s.req = http.get(VIA + '/api/events' + query, { headers: h, agent: false }, (res) => {
  67. s.status = res.statusCode; s.headers = res.headers; res.setEncoding('utf8');
  68. res.on('data', (d) => {
  69. const now = Date.now();
  70. if (s.last) s.maxGap = Math.max(s.maxGap, now - s.last);
  71. s.last = now;
  72. if (s.status !== 200) { s.body += d; return; }
  73. s.raw += d;
  74. let at;
  75. while ((at = s.raw.indexOf('\n\n')) >= 0) {
  76. const block = s.raw.slice(0, at); s.raw = s.raw.slice(at + 2);
  77. const lines = block.split('\n');
  78. if (lines.every(l => l.startsWith(':'))) { s.comments++; continue; }
  79. const data = lines.filter(l => l.startsWith('data: ')).map(l => l.slice(6)).join('\n');
  80. const idl = lines.find(l => l.startsWith('id: '));
  81. let json = null; try { json = JSON.parse(data); } catch {}
  82. s.events.push({ id: idl ? Number(idl.slice(4)) : null, json, at: now });
  83. }
  84. ok();
  85. });
  86. res.on('end', () => { s.open = false; ok(); });
  87. res.on('close', () => { s.open = false; ok(); });
  88. });
  89. s.req.on('error', () => { s.open = false; ok(); });
  90. });
  91. s.close = () => { s.req.destroy(); s.open = false; };
  92. s.kinds = () => s.events.map(e => e.json && e.json.kind);
  93. 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; };
  94. return s;
  95. }
  96. const api = async (method, path, body, token) => {
  97. const r = await fetch(BASE + path, { method, headers: { 'content-type': 'application/json', ...(token ? { authorization: 'Bearer ' + token } : {}) }, body: body ? J(body) : undefined });
  98. let json = null; try { json = await r.json(); } catch {}
  99. return { status: r.status, json };
  100. };
  101. const refusal = async (query, token, headers = {}) => {
  102. const s = subscribe(query, token, headers);
  103. await s.ready; await sleep(100); s.close();
  104. let json = null; try { json = JSON.parse(s.body); } catch {}
  105. return { status: s.status, json, headers: s.headers };
  106. };
  107. let browser = null;
  108. try {
  109. // ---- mission 014 (Apollo's subscriber, 2026-10-19): streams opened AS EARLY AS POSSIBLE must get live events ----------
  110. // `first`: retried from the moment the process starts (like a subscriber retrying through the restart's 502s) — it is
  111. // the very first request the server answers; `second`: opened right after it; the later streams come after the
  112. // server answered /api/projects. Then one write: every one of them must get it within 2 s.
  113. const tStart = Date.now();
  114. let first = null;
  115. for (const end = tStart + COLD_MS; Date.now() < end;) {
  116. const s = subscribe('', K.aliceToken);
  117. await s.ready;
  118. if (s.status === 200 && s.open) { first = s; break; }
  119. s.close(); await sleep(50);
  120. }
  121. if (!first) throw new Error(`no early stream within ${COLD_MS} ms`);
  122. console.log(` (the first stream connected ${Date.now() - tStart} ms after the start, the server's first request)`);
  123. const second = subscribe('', K.aliceToken);
  124. await second.ready;
  125. let up = false;
  126. 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); }
  127. if (!up) throw new Error(`the server did not come up within ${COLD_MS} ms`);
  128. const later = subscribe('', K.aliceToken);
  129. await later.ready;
  130. await sleep(300);
  131. {
  132. const t0 = Date.now();
  133. const w = await api('POST', '/api/projects/alpha/tickets/1/comments', { text: 'early bird' }, K.aliceToken);
  134. check('mission 014: a comment right after the start → 201', w.status === 201, J(w));
  135. 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]]) {
  136. const e = await s.waitFor(e => e.json && e.json.text === 'early bird', 2500);
  137. 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) + ')');
  138. }
  139. for (const s of [first, second, later]) s.close();
  140. }
  141. // ---- refusals -------------------------------------------------------------------------------------------
  142. let r = await refusal('', null);
  143. 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));
  144. r = await refusal('', 'tkt_' + '0'.repeat(48));
  145. check('401 with an unknown token', r.status === 401, J(r));
  146. r = await refusal('', K.aliceToken.slice(0, -2) + 'zz');
  147. check('401 with a malformed token', r.status === 401, J(r));
  148. if (VIA !== BASE) console.log(' (subscribers connect through ' + VIA + ')');
  149. const post = await fetch(VIA + '/api/events', { method: 'POST', headers: { authorization: 'Bearer ' + K.aliceToken } });
  150. check('405 for a POST', post.status === 405, String(post.status));
  151. r = await refusal('?after=abc', K.aliceToken);
  152. check('400 for after=abc (field after)', r.status === 400 && r.json.field === 'after', J(r));
  153. r = await refusal('', K.aliceToken, { 'last-event-id': '-1' });
  154. check('400 for Last-Event-ID: -1', r.status === 400 && r.json.field === 'after', J(r));
  155. r = await refusal('?project=nope', K.aliceToken);
  156. check('400 for an unknown project (field project)', r.status === 400 && r.json.field === 'project' && /nope/.test(r.json.error), J(r));
  157. r = await refusal('?assignee=nobody-here', K.aliceToken);
  158. check('400 for an unknown assignee', r.status === 400 && r.json.field === 'assignee', J(r));
  159. r = await refusal('?project=alpha', K.betaKey);
  160. check('403 for a project key asking for another project', r.status === 403 && r.json.field === 'project', J(r));
  161. r = await refusal('?notMine=1', K.betaKey);
  162. check('400 for notMine with a project key (it writes for many people)', r.status === 400 && r.json.field === 'notMine', J(r));
  163. // ---- the subscribers ---------------------------------------------------------------------------------------
  164. const idle = subscribe('?project=beta&assignee=carol', K.carolToken); // nothing will match for 2 minutes
  165. const all = subscribe('', K.aliceToken);
  166. const alphaBob = subscribe('?project=alpha', K.bobToken);
  167. const key = subscribe('', K.betaKey);
  168. const notMine = subscribe('?notMine=1', K.aliceToken);
  169. const forBob = subscribe('?assignee=bob', K.carolToken);
  170. const both = subscribe(`?project=${K.alpha},beta`, K.carolToken);
  171. const resumer = subscribe('?project=alpha', K.carolToken);
  172. await Promise.all([idle, all, alphaBob, key, notMine, forBob, both, resumer].map(s => s.ready));
  173. 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));
  174. check('a fresh stream (no after) replays nothing', all.events.length === 0, J(all.events));
  175. // ---- a REAL browser: alice comments on alpha #1 and changes its state ----------------------------------------
  176. browser = await launchBrowser({ debugPortRange: CHROME });
  177. const page = await browser.newPage();
  178. await page.send('Network.enable');
  179. await page.send('Network.setCookie', { name: 'hlsid', value: sid, url: BASE, httpOnly: true });
  180. await page.goto(BASE + '/alpha/1');
  181. 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 });
  182. 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); })`);
  183. // click INTO the visual editor (the Comments block's MdEditor, mission 016) and type key by key
  184. const 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 }; })()`);
  185. for (const type of ['mouseMoved', 'mousePressed', 'mouseReleased']) await page.send('Input.dispatchMouseEvent', { type, x: box.x, y: box.y, button: 'left', clickCount: 1 });
  186. const words = 'a comment typed in Chrome';
  187. for (const ch of words) {
  188. await page.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch });
  189. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch });
  190. }
  191. const typed = await page.evaluate('document.querySelector("#commentform md-editor input.value").value');
  192. check('browser: the comment was typed into the editor (its field holds it)', typed === words, J(typed));
  193. let t0 = Date.now();
  194. await page.click('#commentform button.comment-post');
  195. let ev = await all.waitFor(e => e.json && e.json.kind === 'comment' && e.json.text === words, 3000);
  196. check('browser comment → the stream within 1 s', ev && ev.at - t0 < 1000, ev ? (ev.at - t0) + ' ms' : 'nothing arrived: ' + J(all.events));
  197. if (ev) console.log(` (${ev.at - t0} ms after the click)`);
  198. 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));
  199. await page.waitFor('[...document.querySelectorAll("#events li")].some(li => li.textContent.includes("a comment typed in Chrome"))', { label: 'the comment shows on the page' });
  200. // the state change is the composer's State select (real keys: ArrowDown until it shows "progress") and its main button ("Set to progress")
  201. await page.evaluate(`document.querySelector('#commentform select[name=state]').focus()`);
  202. 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++) {
  203. await page.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });
  204. await page.send('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowDown', code: 'ArrowDown', windowsVirtualKeyCode: 40, nativeVirtualKeyCode: 40 });
  205. await sleep(120);
  206. }
  207. 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');
  208. t0 = Date.now();
  209. await page.click('#commentform button.comment-post');
  210. ev = await all.waitFor(e => e.json && e.json.kind === 'state', 3000);
  211. 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));
  212. if (ev) console.log(` (${ev.at - t0} ms after the click)`);
  213. // ---- the API writes: every kind ---------------------------------------------------------------------------
  214. const resumeFrom = (await resumer.waitFor(e => e.json && e.json.kind === 'state', 2000) || {}).id;
  215. resumer.close(); // carol's program drops off here
  216. check('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);
  217. check('alice assigns alpha #1 to bob → 201', (await api('POST', '/api/projects/alpha/tickets/1/assign', { assignee: 'bob' }, K.aliceToken)).status === 201);
  218. check('bob comments on alpha #1 → 201', (await api('POST', '/api/projects/alpha/tickets/1/comments', { text: 'bob on alpha' }, K.bobToken)).status === 201);
  219. check('alice edits alpha #1 → 201', (await api('POST', '/api/projects/alpha/tickets/1/edit', { summary: 'the summary, edited' }, K.aliceToken)).status === 201);
  220. const made = await api('POST', '/api/projects/alpha/tickets', { subject: 'alpha two', summary: 'x'.repeat(400) }, K.aliceToken);
  221. check('alice opens alpha #2 → 201', made.status === 201, J(made));
  222. 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);
  223. check('bob moves beta #1 to done → 201', (await api('POST', '/api/projects/beta/tickets/1/state', { state: 'done' }, K.bobToken)).status === 201);
  224. await all.waitFor(e => e.json && e.json.kind === 'state' && e.json.project === 'beta', 2000);
  225. await sleep(300);
  226. const want = ['comment', 'state', 'comment', 'assign', 'comment', 'edit', 'created', 'link', 'state'];
  227. check('alice (no filter) got every event in order: ' + want.join(' '), J(all.kinds()) === J(want), J(all.kinds()));
  228. const ids = all.events.map(e => e.id);
  229. check('event ids increase by one, no gaps, no doubles', ids.every((v, i) => i === 0 || v === ids[i - 1] + 1), J(ids));
  230. const byKind = (s, k, p) => s.events.find(e => e.json.kind === k && (!p || e.json.project === p));
  231. const cr = byKind(all, 'created');
  232. 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));
  233. const ed = byKind(all, 'edit');
  234. check('edit: the new summary', ed && ed.json.text === 'the summary, edited', ed && J(ed.json));
  235. const as = byKind(all, 'assign');
  236. 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));
  237. const lk = byKind(all, 'link');
  238. 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));
  239. const done = all.events.find(e => e.json.kind === 'state' && e.json.project === 'beta');
  240. check('state: beta #1 → done', done && done.json.state === 'done' && done.json.actor === 'bob', done && J(done.json));
  241. // ---- filters ------------------------------------------------------------------------------------------------
  242. const projOf = (s) => [...new Set(s.events.map(e => e.json.project))].sort();
  243. check('project=alpha (bob): only alpha events (7)', J(projOf(alphaBob)) === J(['alpha']) && alphaBob.events.length === 7, J(alphaBob.kinds()));
  244. check('project=<alpha id>,beta: both projects, all 9', J(projOf(both)) === J(['alpha', 'beta']) && both.events.length === 9, J(both.kinds()));
  245. 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)));
  246. 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])));
  247. 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()));
  248. // ---- resume: carol's program missed what happened after the state change -------------------------------
  249. const missed = all.events.filter(e => e.id > resumeFrom && e.json.project === 'alpha').map(e => e.id);
  250. const back = subscribe('?project=alpha', K.carolToken, { 'last-event-id': String(resumeFrom) });
  251. await back.ready;
  252. await back.waitFor(e => e.id === missed[missed.length - 1], 2000);
  253. await sleep(200);
  254. 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));
  255. const viaQuery = subscribe(`?project=alpha&after=${resumeFrom}`, K.carolToken);
  256. await viaQuery.ready; await viaQuery.waitFor(e => e.id === missed[missed.length - 1], 2000); await sleep(200);
  257. check('the same with ?after=', J(viaQuery.events.map(e => e.id)) === J(missed), J(viaQuery.events.map(e => e.id)));
  258. const header = subscribe(`?project=alpha&after=1`, K.carolToken, { 'last-event-id': String(resumeFrom) });
  259. await header.ready; await sleep(400);
  260. check('Last-Event-ID wins over ?after=', J(header.events.map(e => e.id)) === J(missed), J(header.events.map(e => e.id)));
  261. viaQuery.close(); header.close();
  262. 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);
  263. const live = await back.waitFor(e => e.json.text === 'after the resume', 2000);
  264. await sleep(300);
  265. 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)));
  266. const fromZero = subscribe('?after=0', K.aliceToken);
  267. await fromZero.ready; await sleep(500);
  268. const total = all.events[all.events.length - 1].id;
  269. 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)));
  270. fromZero.close(); back.close();
  271. // ---- other clients: Hybriel (hl:fetch stream mode) and Python (urllib) ------------------------------------------
  272. 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' } });
  273. children.push(hlc);
  274. let hlOut = ''; hlc.stdout.on('data', d => hlOut += d); hlc.stderr.on('data', d => hlOut += d);
  275. let hlClosed = false; hlc.on('close', () => { hlClosed = true; }); // 'close' = exited AND its output read
  276. const py = spawn('python3', ['-I', '-c', `
  277. import urllib.request, json, sys
  278. req = urllib.request.Request(sys.argv[1] + '/api/events?project=beta', headers={'Authorization': 'Bearer ' + sys.argv[2]})
  279. with urllib.request.urlopen(req, timeout=20) as r:
  280. print('STATUS', r.status, flush=True)
  281. for raw in r:
  282. line = raw.decode().rstrip('\\n')
  283. if line.startswith('data: '):
  284. print('EVENT', line[6:], flush=True)
  285. break
  286. `, VIA, K.bobToken]);
  287. children.push(py);
  288. let pyOut = ''; py.stdout.on('data', d => pyOut += d); py.stderr.on('data', d => pyOut += d);
  289. for (let i = 0; i < 40 && !/STATUS 200/.test(pyOut); i++) await sleep(100);
  290. 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);
  291. for (let i = 0; i < 60 && !/EVENT/.test(pyOut); i++) await sleep(100);
  292. // the Hybriel client compiles at its first start (cold ~20 s, hybriel#148); it replays from after=0, so waiting is safe
  293. for (const end = Date.now() + COLD_MS; !/DONE/.test(hlOut) && !hlClosed && Date.now() < end;) await sleep(100);
  294. const pyEv = (pyOut.split('\n').find(l => l.startsWith('EVENT ')) || '').slice(6);
  295. check('Python (urllib) reads the live event', /"text":"for python"/.test(pyEv), pyOut);
  296. const hlEvs = hlOut.split('\n').filter(l => l.startsWith('EVENT ')).map(l => JSON.parse(l.slice(6)));
  297. 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));
  298. // ---- the idle stream: 2 minutes without a matching event --------------------------------------------------
  299. await page.close().catch(() => {});
  300. const left = IDLE_MS - (Date.now() - idle.started);
  301. if (left > 0) { console.log(` (waiting ${Math.round(left / 1000)} s more for the idle stream)`); await sleep(left); }
  302. 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 }));
  303. 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);
  304. const late = await idle.waitFor(e => e.json.kind === 'assign', 2000);
  305. check('… and the 2-minute idle stream still delivers it', !!late && late.json.assignee === 'carol', J(idle.events));
  306. for (const s of [idle, all, alphaBob, key, notMine, forBob, both]) s.close();
  307. // Mission 030: a note edit does not replace or relabel the numbered state event.
  308. const noteState = await api('POST', '/api/projects/alpha/tickets/1/state', { state: 'done', text: 'original state note' }, K.aliceToken);
  309. check('m030: create a state transition with a note', noteState.status === 201 && noteState.json.event.kind === 'state', J(noteState));
  310. const noteEdit = await api('POST', '/api/projects/alpha/tickets/1/comments/' + noteState.json.event.id + '/edit', { text: 'edited state note' }, K.aliceToken);
  311. 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));
  312. const noteReplay = subscribe('?project=alpha&after=0', K.aliceToken);
  313. try {
  314. await noteReplay.ready;
  315. const originalState = await noteReplay.waitFor(e => e.json.kind === 'state' && e.json.text === 'original state note', 2000);
  316. 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)));
  317. } finally { noteReplay.close(); }
  318. } catch (e) {
  319. check('the test ran to its end', false, e.stack + '\n' + log.slice(-2000));
  320. } finally {
  321. for (const c of children) { try { c.kill('SIGKILL'); } catch {} }
  322. if (browser) await browser.close().catch(() => {});
  323. server.kill('SIGTERM');
  324. await sleep(500);
  325. try { process.kill(server.pid, 'SIGKILL'); } catch {}
  326. writeFileSync(join(STORE, 'server.log'), log);
  327. }
  328. const errors = log.split('\n').filter(l => /error/i.test(l) && !/error absorbed/.test(l));
  329. check('the server log has no errors', errors.length === 0, errors.slice(0, 5).join(' | '));
  330. console.log(`\n${passes} passed, ${failures} failed`);
  331. 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