gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit8a460b168a460b16mission 014: Apollo's 'stream opened right after the start gets no live events' is not a tickets bug — events.mjs checks early streamsmre8a460b16/tests/events.mjs

25.7 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")', { 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 (in the md-editor's shadow root) and type key by key
  184. const 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 }; })()`);
  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("#commenttext").value');
  192. check('browser: the comment was typed into the editor (the textarea holds it)', typed === words, J(typed));
  193. let t0 = Date.now();
  194. await page.click('#commentsend');
  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. await page.evaluate(`(() => { const i = document.querySelector('#newstate'); i.value = 'progress'; i.dispatchEvent(new Event('change', { bubbles: true })); })()`);
  201. t0 = Date.now();
  202. await page.click('#statesend');
  203. ev = await all.waitFor(e => e.json && e.json.kind === 'state', 3000);
  204. 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));
  205. if (ev) console.log(` (${ev.at - t0} ms after the click)`);
  206. // ---- the API writes: every kind ---------------------------------------------------------------------------
  207. const resumeFrom = (await resumer.waitFor(e => e.json && e.json.kind === 'state', 2000) || {}).id;
  208. resumer.close(); // carol's program drops off here
  209. 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);
  210. check('alice assigns alpha #1 to bob → 201', (await api('POST', '/api/projects/alpha/tickets/1/assign', { assignee: 'bob' }, K.aliceToken)).status === 201);
  211. check('bob comments on alpha #1 → 201', (await api('POST', '/api/projects/alpha/tickets/1/comments', { text: 'bob on alpha' }, K.bobToken)).status === 201);
  212. check('alice edits alpha #1 → 201', (await api('POST', '/api/projects/alpha/tickets/1/edit', { summary: 'the summary, edited' }, K.aliceToken)).status === 201);
  213. const made = await api('POST', '/api/projects/alpha/tickets', { subject: 'alpha two', summary: 'x'.repeat(400) }, K.aliceToken);
  214. check('alice opens alpha #2 → 201', made.status === 201, J(made));
  215. 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);
  216. check('bob moves beta #1 to done → 201', (await api('POST', '/api/projects/beta/tickets/1/state', { state: 'done' }, K.bobToken)).status === 201);
  217. await all.waitFor(e => e.json && e.json.kind === 'state' && e.json.project === 'beta', 2000);
  218. await sleep(300);
  219. const want = ['comment', 'state', 'comment', 'assign', 'comment', 'edit', 'created', 'link', 'state'];
  220. check('alice (no filter) got every event in order: ' + want.join(' '), J(all.kinds()) === J(want), J(all.kinds()));
  221. const ids = all.events.map(e => e.id);
  222. check('event ids increase by one, no gaps, no doubles', ids.every((v, i) => i === 0 || v === ids[i - 1] + 1), J(ids));
  223. const byKind = (s, k, p) => s.events.find(e => e.json.kind === k && (!p || e.json.project === p));
  224. const cr = byKind(all, 'created');
  225. 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));
  226. const ed = byKind(all, 'edit');
  227. check('edit: the new summary', ed && ed.json.text === 'the summary, edited', ed && J(ed.json));
  228. const as = byKind(all, 'assign');
  229. 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));
  230. const lk = byKind(all, 'link');
  231. 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));
  232. const done = all.events.find(e => e.json.kind === 'state' && e.json.project === 'beta');
  233. check('state: beta #1 → done', done && done.json.state === 'done' && done.json.actor === 'bob', done && J(done.json));
  234. // ---- filters ------------------------------------------------------------------------------------------------
  235. const projOf = (s) => [...new Set(s.events.map(e => e.json.project))].sort();
  236. check('project=alpha (bob): only alpha events (7)', J(projOf(alphaBob)) === J(['alpha']) && alphaBob.events.length === 7, J(alphaBob.kinds()));
  237. check('project=<alpha id>,beta: both projects, all 9', J(projOf(both)) === J(['alpha', 'beta']) && both.events.length === 9, J(both.kinds()));
  238. 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)));
  239. 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])));
  240. 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()));
  241. // ---- resume: carol's program missed what happened after the state change -------------------------------
  242. const missed = all.events.filter(e => e.id > resumeFrom && e.json.project === 'alpha').map(e => e.id);
  243. const back = subscribe('?project=alpha', K.carolToken, { 'last-event-id': String(resumeFrom) });
  244. await back.ready;
  245. await back.waitFor(e => e.id === missed[missed.length - 1], 2000);
  246. await sleep(200);
  247. 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));
  248. const viaQuery = subscribe(`?project=alpha&after=${resumeFrom}`, K.carolToken);
  249. await viaQuery.ready; await viaQuery.waitFor(e => e.id === missed[missed.length - 1], 2000); await sleep(200);
  250. check('the same with ?after=', J(viaQuery.events.map(e => e.id)) === J(missed), J(viaQuery.events.map(e => e.id)));
  251. const header = subscribe(`?project=alpha&after=1`, K.carolToken, { 'last-event-id': String(resumeFrom) });
  252. await header.ready; await sleep(400);
  253. check('Last-Event-ID wins over ?after=', J(header.events.map(e => e.id)) === J(missed), J(header.events.map(e => e.id)));
  254. viaQuery.close(); header.close();
  255. 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);
  256. const live = await back.waitFor(e => e.json.text === 'after the resume', 2000);
  257. await sleep(300);
  258. 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)));
  259. const fromZero = subscribe('?after=0', K.aliceToken);
  260. await fromZero.ready; await sleep(500);
  261. const total = all.events[all.events.length - 1].id;
  262. 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)));
  263. fromZero.close(); back.close();
  264. // ---- other clients: Hybriel (hl:fetch stream mode) and Python (urllib) ------------------------------------------
  265. 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' } });
  266. children.push(hlc);
  267. let hlOut = ''; hlc.stdout.on('data', d => hlOut += d); hlc.stderr.on('data', d => hlOut += d);
  268. let hlClosed = false; hlc.on('close', () => { hlClosed = true; }); // 'close' = exited AND its output read
  269. const py = spawn('python3', ['-I', '-c', `
  270. import urllib.request, json, sys
  271. req = urllib.request.Request(sys.argv[1] + '/api/events?project=beta', headers={'Authorization': 'Bearer ' + sys.argv[2]})
  272. with urllib.request.urlopen(req, timeout=20) as r:
  273. print('STATUS', r.status, flush=True)
  274. for raw in r:
  275. line = raw.decode().rstrip('\\n')
  276. if line.startswith('data: '):
  277. print('EVENT', line[6:], flush=True)
  278. break
  279. `, VIA, K.bobToken]);
  280. children.push(py);
  281. let pyOut = ''; py.stdout.on('data', d => pyOut += d); py.stderr.on('data', d => pyOut += d);
  282. for (let i = 0; i < 40 && !/STATUS 200/.test(pyOut); i++) await sleep(100);
  283. 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);
  284. for (let i = 0; i < 60 && !/EVENT/.test(pyOut); i++) await sleep(100);
  285. // the Hybriel client compiles at its first start (cold ~20 s, hybriel#148); it replays from after=0, so waiting is safe
  286. for (const end = Date.now() + COLD_MS; !/DONE/.test(hlOut) && !hlClosed && Date.now() < end;) await sleep(100);
  287. const pyEv = (pyOut.split('\n').find(l => l.startsWith('EVENT ')) || '').slice(6);
  288. check('Python (urllib) reads the live event', /"text":"for python"/.test(pyEv), pyOut);
  289. const hlEvs = hlOut.split('\n').filter(l => l.startsWith('EVENT ')).map(l => JSON.parse(l.slice(6)));
  290. 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));
  291. // ---- the idle stream: 2 minutes without a matching event --------------------------------------------------
  292. await page.close().catch(() => {});
  293. const left = IDLE_MS - (Date.now() - idle.started);
  294. if (left > 0) { console.log(` (waiting ${Math.round(left / 1000)} s more for the idle stream)`); await sleep(left); }
  295. 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 }));
  296. 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);
  297. const late = await idle.waitFor(e => e.json.kind === 'assign', 2000);
  298. check('… and the 2-minute idle stream still delivers it', !!late && late.json.assignee === 'carol', J(idle.events));
  299. for (const s of [idle, all, alphaBob, key, notMine, forBob, both]) s.close();
  300. } catch (e) {
  301. check('the test ran to its end', false, e.stack + '\n' + log.slice(-2000));
  302. } finally {
  303. for (const c of children) { try { c.kill('SIGKILL'); } catch {} }
  304. if (browser) await browser.close().catch(() => {});
  305. server.kill('SIGTERM');
  306. await sleep(500);
  307. try { process.kill(server.pid, 'SIGKILL'); } catch {}
  308. writeFileSync(join(STORE, 'server.log'), log);
  309. }
  310. const errors = log.split('\n').filter(l => /error/i.test(l) && !/error absorbed/.test(l));
  311. check('the server log has no errors', errors.length === 0, errors.slice(0, 5).join(' | '));
  312. console.log(`\n${passes} passed, ${failures} failed`);
  313. process.exit(failures ? 1 : 0);

Branches

Latest commits

  • 8a460b16mission 014: Apollo's 'stream opened right after the start gets no live events' is not a tickets bug — events.mjs checks early streamsmre
  • 6309ca81mission brief 014mre
  • c1161469mission 013: GitHub pipe tables on ticket pages (lib/markdown.hl + View + CSS) and re-vendor hybriel master a832f73bmre
  • a30b5d12mission brief (w13)mre
  • b50a6f93w9 (tickets): re-vendor hybriel 9f912f3b (#146 emit in a lib static, #147) — the 12 live-push emits in lib/api.hl compile as they are; cold start (#148): tests wait TICKETS_COLD_MS for every start, deploy.sh gates browser + events and waits up to 120 s for the URL, container /tmp tmpfs + hybriel-cache volume; events-client stops at EVENTS_MAX inside a chunk; connect.mjs ports by env. bin/hybriel sha256 7421907868ac07d8a7d08296b083c6f8b20407d0e099ce4bebbf7ae053d9060a. Gates (8720–8739): browser 315/0 (+ all-cold 315/0), events 48/0 cold, connect 60/0, short-id 19/0; real-data copy old 0e8a41c vs new: 2,425 reads + 72 writes identical after masking ?v hashes, offline at, route order; event stream on the copy delivers. Not deployed.mre
  • 43be6578w9: re-vendor hybriel master edfd400a; event stream imports sseStart/sseSend/sseAlive from hl:http1 (hybriel#144), useTransport gone; tools/import.hl plain declarations. BLOCKED: hybriel-native refuses `emit client` in a static (lib/api.hl) — the server does not compile on edfd400a, gates fail at start; scratch copy without those emits: events 48/0, gate 254 ok up to the first live pushmre
  • 0e8a41caw6 (ticket #26): event stream for programs — GET /api/events (Server-Sent Events)mre
  • bb64d57cmission 012 (ticket #25 API part): every /api/projects/<x>/… route takes the project's id (12-char record id) as well as its slug, same answers byte for byte; tickets stay under their project, no global /api/tickets/<x>. gate 315/0 (old code: the 13 id checks fail), connect 60/0, live-data copy old vs new 1,484 identical, slug vs id 772 identicalmre
  • 7538b034mission 011 (ticket #25 web part): short page URLs /<slug> and /<slug>/<number>; /projects/<slug>, /projects/<slug>/<n>, /projects/<slug>/tickets/<n> and /tickets/<ref> answer 301 (current slug); slug pages moved behind hl:web's own routes after construction (they answered /__hl/* and /components/*.hl); reserved slugs refused; API paths unchanged. gate 293/0, connect 60/0, live-data copy 187/0, API old vs new: only page links differmre
  • 0369106emission 010 (code order) 4/4: README file map + import order + 'Same output' test, STATUS (entry, lessons, how to verify), LOG, report; tests/realdata-baseline.mjs + realdata-compare*.py (a cleanup answers the same on live data), tests/letcount.pymre
  • a75e0279mission 010 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (456 lets → plain declarations; Hybriel refuses a plain declaration inside a loop on its 2nd pass). gate 249/0, connect 60/0, real-data reads identical, a 50-step write sequence (API + faces) identical to the old codemre
  • e9d5c618mission 010 (code order) 2/4: one lib/ file per topic — store.hl split into projects / tickets (+ relations) / events / tickets-helpers, util.hl shared helpers (env, storage dir, URLs, sorts, Vienna time), the function routes out of project.hl into lib/api.hl (thin; auth/filters/Accept in api-helpers.hl), invite + member-removal logic out of the faces/routes into invites.hl / tickets.hl; project.hl is the map. /login/callback gets req + the session store by reference. gate 249/0, connect 60/0, real-data reads identicalmre
  • 97e269b5mission 010 (code order) 1/4: .hl files out of the root — lib/ (store, users, connections, invites, migrate, markdown, mdview, import = ticketfile, util = localtime, jsoncheck, api-helpers = api), tools/import.hl, components/styles.hl; import paths only. gate 249/0, connect 60/0, real-data reads identicalmre
  • 38f9d10ftickets: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gate 249/0, connect 60/0mre
  • d3db6139tickets: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 249/0, connect 60/0mre
  • bce182e3tickets: Hybriel master 7eea0d32 (#126 memory, #48 lambda copies its argument); migrate.hl lambdas take &logmre
  • 4137be0fantcolony#40: mission references point to the moved missionsmre
  • 9bfba36aantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • c7bd2645tickets: Hybriel master 73267707 (#122 fixed); compactNow workaround removed (#110 covered)mre
  • 2ab91ee9tickets: gate checks rows appear once (session sync); re-vendor to ff51cf46 stopped on hybriel#122, stays 837fe120mre