gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit8d8e20538d8e2053Document subscription contract and exercise delta deliverymre8d8e2053/tests/subscriptions.mjs

11.2 KB

  1. // Ticket #51 contract against an isolated store and a real HTTP fake waker.
  2. import { spawn, spawnSync } from 'node:child_process';
  3. import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
  4. import { resolve, join } from 'node:path';
  5. import http from 'node:http';
  6. import { createHmac } from 'node:crypto';
  7. const APP = process.env.SUBSCRIPTIONS_APP || resolve(new URL('..', import.meta.url).pathname);
  8. const BIN = join(APP, 'bin/hybriel');
  9. const STORE = join(APP, '.scratch/subscriptions');
  10. const BASE = 'http://127.0.0.1:8740';
  11. const sleep = ms => new Promise(r => setTimeout(r, ms));
  12. let passed = 0, failed = 0, log = '', server;
  13. function check(label, ok, detail = '') { console.log(`${ok ? 'ok' : 'FAIL'} ${label}${ok ? '' : ': ' + JSON.stringify(detail)}`); ok ? passed++ : failed++; }
  14. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  15. const env = { ...process.env, HL_HOST: '127.0.0.1', HL_PORT_BASE: '8742', TICKETS_STORAGE: join(STORE, 'mpackdb'), TICKETS_SESSIONS: join(STORE, 'sessions'), TICKETS_PORT: '8740', TICKETS_WATCH: '0', TICKETS_PUBLIC_URL: BASE, TICKETS_WAKER_URL: 'http://127.0.0.1:8741/wake', TICKETS_WAKER_SECRET: 'test-secret' };
  16. const seed = spawnSync(BIN, ['tests/events-seed.hl'], { cwd: APP, env, encoding: 'utf8', timeout: 120000 });
  17. const line = seed.stdout?.split('\n').find(l => l.startsWith('SEED '));
  18. if (!line) throw Error(seed.stdout + seed.stderr);
  19. const K = JSON.parse(line.slice(5));
  20. const wakes = [];
  21. let reject = false;
  22. const fake = http.createServer(async (req, res) => {
  23. let raw = ''; for await (const d of req) raw += d;
  24. const expected = 'sha256=' + createHmac('sha256', 'test-secret').update(raw).digest('hex');
  25. const valid = req.headers['x-worldapi-signature-256'] === expected;
  26. const body = JSON.parse(raw); wakes.push({ body, valid }); res.writeHead(valid && !reject ? 204 : 503).end();
  27. });
  28. await new Promise(r => fake.listen(8741, '127.0.0.1', r));
  29. const api = async (path, method='GET', body, token=K.aliceToken, md=false) => {
  30. const response = await fetch(BASE + path, { method, headers: { ...(token ? { authorization: 'Bearer ' + token } : {}), 'content-type': 'application/json', ...(md ? { accept: 'text/markdown' } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
  31. const text = await response.text(); let data; try { data = JSON.parse(text); } catch {}
  32. return { status: response.status, data, text, headers: response.headers };
  33. };
  34. async function start() {
  35. server = spawn(BIN, ['project.hl'], { cwd: APP, env });
  36. console.log('PROCESS tickets', server.pid); server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  37. for (const end=Date.now()+120000; Date.now()<end;) { try { if ((await api('/api/projects')).status === 200) return; } catch {} await sleep(200); }
  38. throw Error('server did not start: '+log);
  39. }
  40. async function stop() { if (server && server.exitCode === null) { server.kill('SIGTERM'); await Promise.race([new Promise(r=>server.once('exit',r)), sleep(3000)]); if (server.exitCode === null) server.kill('SIGKILL'); } }
  41. const sub = (id, suffix='delta') => '/api/subscriptions/' + id + '/' + suffix;
  42. const comment = (text, token=K.bobToken) => api('/api/projects/alpha/tickets/1/comments', 'POST', {text}, token);
  43. try {
  44. const kat = spawnSync(BIN, ['tests/subscriptions-hmac.hl'], { cwd: APP, env, encoding: 'utf8', timeout:120000 });
  45. check('HMAC known answer', kat.stdout.trim() === 'sha256=f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8', kat.stdout+kat.stderr);
  46. await start();
  47. check('no token refused', (await api('/api/subscriptions','GET',undefined,null)).status===401);
  48. check('project key refused', (await api('/api/subscriptions','GET',undefined,K.betaKey)).status===401);
  49. let r=await api('/api/subscriptions','POST',{projects:[K.alpha],owner:K.carol},K.bobToken);
  50. check('nonadmin for another user refused',r.status===403,r);
  51. r=await api('/api/subscriptions','POST',{projects:'all',owner:K.bob}); check('all for another user refused',r.status===403,r);
  52. r=await api('/api/subscriptions','POST',{projects:[K.alpha],owner:K.bob,label:'bob alpha'});
  53. check('admin subscribes another user',r.status===201,r);
  54. const other=r.data?.subscription?.id;
  55. r=await api('/api/subscriptions','POST',{projects:[K.alpha],label:'alice alpha'});
  56. check('create self baseline',r.status===201 && r.data.subscription.cursor>=2,r);
  57. const id=r.data?.subscription?.id;
  58. check('list own and administered', (await api('/api/subscriptions')).data.subscriptions.length===2);
  59. check('other cannot fetch', (await api(sub(id),'GET',undefined,K.bobToken)).status===403);
  60. check('other cannot remove', (await api(sub(id,'remove'),'POST',{},K.bobToken)).status===403);
  61. check('baseline empty', (await api(sub(id))).data.tickets.length===0);
  62. await comment('self only',K.aliceToken); await sleep(250);
  63. check('own events absent', (await api(sub(id)+'?peek=1')).data.tickets.length===0);
  64. check('own events never wake own subscription', wakes.every(w=>w.body.subscription!==id));
  65. check('comment write succeeds',(await comment('hello alice')).status===201);
  66. await sleep(300);
  67. const first=wakes.filter(w=>w.body.subscription===id);
  68. check('one signed content-free wake', first.length===1 && first[0].valid && Object.keys(first[0].body).sort().join() === 'at,delivery,subscription',first);
  69. await comment('second alice'); await sleep(300);
  70. check('no further wakes pending',wakes.filter(w=>w.body.subscription===id).length===1);
  71. for (const state of ['review','done']) await api('/api/projects/alpha/tickets/1/state','POST',{state},K.aliceToken);
  72. // bob has use role; temporarily promote so he can generate both state events, while self exclusion stays mandatory.
  73. await api('/api/projects/alpha/members','POST',{user:K.bob,role:'edit'});
  74. await api('/api/projects/alpha/tickets/1/state','POST',{state:'open'},K.bobToken);
  75. await api('/api/projects/alpha/tickets/1/state','POST',{state:'review'},K.bobToken);
  76. await api('/api/projects/alpha/tickets/1/state','POST',{state:'done'},K.bobToken);
  77. await api('/api/projects/alpha/tickets/1/assign','POST',{assignee:K.bob},K.bobToken);
  78. await api('/api/projects/alpha/tickets/1/assign','POST',{assignee:K.alice},K.bobToken);
  79. await api('/api/projects/alpha/tickets/1/edit','POST',{subject:'edited',summary:'alice summary'},K.bobToken);
  80. await api('/api/projects/alpha/tickets/1/blocked-by','POST',{add:'beta#1'},K.bobToken);
  81. r=await api(sub(id)+'?peek=1'); const t=r.data.tickets[0];
  82. check('merged per ticket',r.data.tickets.length===1 && t.changes.state.from==='done' && t.changes.state.to==='done',r.data);
  83. check('comments and full last snippet',t.changes.comments===2 && t.changes.lastComment==='second alice',t);
  84. check('all relevance markers', ['assigned','own','mention'].every(x=>t.relevance.includes(x)),t);
  85. check('edit, assignment and links', t.changes.titleEdited && t.changes.summaryEdited && t.changes.assignee.to===K.alice && t.changes.links.length===1,t);
  86. check('JSON shape', ['subscription','from','upTo','tickets','more'].every(k=>k in r.data) && t.href===BASE+'/alpha/1' && t.actors.includes(K.bob),r.data);
  87. check('peek keeps pending',(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakePending);
  88. r=await api(sub(id),'GET',undefined,K.aliceToken,true);
  89. check('Markdown shape',r.status===200 && r.headers.get('content-type').startsWith('text/markdown') && r.text.includes('alpha#1') && r.text.includes('2 comments'),r);
  90. check('fetch drains', (await api(sub(id))).data.tickets.length===0);
  91. check('fetch clears wakePending',!(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakePending);
  92. await comment('after fetch'); await sleep(300);
  93. check('new episode wakes',wakes.filter(w=>w.body.subscription===id).length===2);
  94. await stop(); await start(); await sleep(400);
  95. const restarted=wakes.filter(w=>w.body.subscription===id);
  96. check('restart rewakes same delivery',restarted.length===3 && restarted[1].body.delivery===restarted[2].body.delivery,restarted);
  97. await api(sub(id));
  98. // Lots of tickets exercise byte cap and project overflow, all from non-owner bob.
  99. for (let i=0;i<35;i++) await api('/api/projects/alpha/tickets','POST',{subject:'bulk '+i+' '+ '界'.repeat(60),summary:'bulk'},K.bobToken);
  100. r=await api(sub(id)+'?peek=1','GET',undefined,K.aliceToken,true);
  101. check('Markdown UTF-8 cap and summary',Buffer.byteLength(r.text)<=4096 && /… and \d+ more tickets in alpha \(\d+\)/.test(r.text),r.text);
  102. check('JSON retains overflow', (await api(sub(id)+'?peek=1')).data.tickets.length===35);
  103. r=await api(sub(other,'remove'),'POST',{}); check('admin removes',r.status===200,r);
  104. r=await api(sub(id,'remove'),'POST',{}); check('owner removes',r.status===200,r);
  105. check('removed route 404',(await api(sub(id))).status===404);
  106. // Main/standby overlap: only main may send; a disabled standby writes to the same numbered store.
  107. const standby = spawn(BIN, ['project.hl'], {cwd: APP, env: {...env,TICKETS_PORT:'8752',TICKETS_WAKES_DISABLED:'1'}});
  108. console.log('PROCESS standby',standby.pid);
  109. standby.stdout.on('data',d=>log+=d); standby.stderr.on('data',d=>log+=d);
  110. try {
  111. for(const end=Date.now()+120000;Date.now()<end;){try{if((await fetch('http://127.0.0.1:8752/api/projects')).ok)break;}catch{} await sleep(200);}
  112. r=await api('/api/subscriptions','POST',{projects:[K.alpha]}); const pending=r.data.subscription.id;
  113. const mark=wakes.length;
  114. await fetch('http://127.0.0.1:8752/api/projects/alpha/tickets/1/comments',{method:'POST',headers:{authorization:'Bearer '+K.bobToken,'content-type':'application/json'},body:JSON.stringify({text:'from standby'})});
  115. await sleep(1600);
  116. check('standby write gets one main wake',wakes.slice(mark).filter(w=>w.body.subscription===pending).length===1,wakes.slice(mark));
  117. await api(sub(pending,'remove'),'POST',{});
  118. } finally { standby.kill('SIGTERM'); await Promise.race([new Promise(r=>standby.once('exit',r)),sleep(3000)]); if(standby.exitCode===null)standby.kill('SIGKILL'); }
  119. // Create one rejected episode, then exercise actual HTTP retries with test-only due-time advancement.
  120. reject=true;
  121. r=await api('/api/subscriptions','POST',{projects:[K.alpha]}); const failing=r.data.subscription.id;
  122. await comment('retry me'); await sleep(300); await stop();
  123. const retryMark=wakes.length;
  124. const retry=spawn(BIN,['tests/subscriptions-retry.hl'],{cwd:APP,env}); console.log('PROCESS retries',retry.pid);
  125. let retryLog=''; retry.stdout.on('data',d=>retryLog+=d);retry.stderr.on('data',d=>retryLog+=d);
  126. const done=await Promise.race([new Promise(r=>retry.once('exit',r)),sleep(120000).then(()=> 'timeout')]);
  127. if(done==='timeout')retry.kill('SIGKILL');
  128. check('failed wake retries then failed after five attempts',done===0 && /FAILED_AFTER 5/.test(retryLog) && wakes.length-retryMark===5,retryLog);
  129. const delays=[...retryLog.matchAll(/RETRY (\d+) DELAY ([\d.]+)/g)].map(m=>Number(m[2]));
  130. check('retry delays 1, 5, 30, 120 minutes',delays.length===4 && delays.every((v,i)=>Math.abs(v-[1,5,30,120][i])<0.02),retryLog);
  131. reject=false; await start(); await sleep(300);
  132. check('restart recovers failed undelivered subscription',(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===failing).wakeStatus==='sent');
  133. await api(sub(failing,'remove'),'POST',{});
  134. } catch(e) { check('suite completed',false,e.stack); }
  135. finally { await stop(); await new Promise(r=>fake.close(r)); writeFileSync(join(STORE,'server.log'),log); }
  136. console.log(`${passed} passed, ${failed} failed`); process.exitCode=failed?1:0;

Branches

Latest commits

  • 8d8e2053Document subscription contract and exercise delta deliverymre
  • fd23726aAdd subscription delta API and signed wake bridgemre
  • c5d28fb5Tickets conductor: S51 startedmre
  • fd6ca1e6Tickets conductor: brief 027 waker design, push-test projectmre
  • e448e656Tickets conductor: STATUS #51mre
  • 1c10857bTickets conductor: P51 eval, brief 027mre
  • e725969dTickets conductor: #51 directionmre
  • 1b5c63ddTickets conductor: P51 startedmre
  • 9f13fbdaTickets conductor: brief 026 prioritymre
  • acc477d9Tickets conductor: brief 026 + Vinzenz recommendationsmre
  • 9233a734Tickets conductor: brief 026 completemre
  • 5da589fdTickets conductor: brief 026 + Gitoria's answermre
  • a3cd5329Tickets conductor: tickets#51 opened, brief 026 draftmre
  • 6f6e5797Tickets conductor: STATUS wordingmre
  • 957de51fTickets conductor: T36 live, #36 review, #50 donemre
  • bc2fde32Merge branch 'main' into t36-stylemre
  • b7ca093atests: wait for the new row and normalize editor marker spacesmre
  • 41da3525Tickets conductor: flake cause, T36 deploy stepmre
  • 64c477e6Tickets conductor: deploy waits for Arachnemre
  • 467d7286Tickets conductor: T36 done, deploy questionmre