tickets
All repositories: gitoria
11.9 KB
// Ticket #51 contract against an isolated store and a real HTTP fake waker.import { spawn, spawnSync } from 'node:child_process';import { mkdirSync, rmSync, writeFileSync } from 'node:fs';import { resolve, join } from 'node:path';import http from 'node:http';import { createHmac } from 'node:crypto';const APP = process.env.SUBSCRIPTIONS_APP || resolve(new URL('..', import.meta.url).pathname);const BIN = join(APP, 'bin/hybriel');const STORE = join(APP, '.scratch/subscriptions');const PORT=Number(process.env.SUBSCRIPTIONS_PORT || 8740);const BASE = 'http://127.0.0.1:'+PORT;const sleep = ms => new Promise(r => setTimeout(r, ms));let passed = 0, failed = 0, log = '', server;function check(label, ok, detail = '') { console.log(`${ok ? 'ok' : 'FAIL'} ${label}${ok ? '' : ': ' + JSON.stringify(detail)}`); ok ? passed++ : failed++; }rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });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: String(PORT), TICKETS_WATCH: '0', TICKETS_PUBLIC_URL: BASE, TICKETS_WAKER_URL: 'http://127.0.0.1:'+(PORT+1)+'/wake', TICKETS_WAKER_SECRET: 'test-secret' };const seed = spawnSync(BIN, ['tests/events-seed.hl'], { cwd: APP, env, encoding: 'utf8', timeout: 120000 });const line = seed.stdout?.split('\n').find(l => l.startsWith('SEED '));if (!line) throw Error(seed.stdout + seed.stderr);const K = JSON.parse(line.slice(5));const wakes = [];let reject = false;const fake = http.createServer(async (req, res) => {let raw = ''; for await (const d of req) raw += d;const expected = 'sha256=' + createHmac('sha256', 'test-secret').update(raw).digest('hex');const valid = req.headers['x-worldapi-signature-256'] === expected;const body = JSON.parse(raw); wakes.push({ body, valid }); res.writeHead(valid && !reject ? 204 : 503).end();});await new Promise(r => fake.listen(PORT+1, '127.0.0.1', r));const api = async (path, method='GET', body, token=K.aliceToken, md=false) => {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) });const text = await response.text(); let data; try { data = JSON.parse(text); } catch {}return { status: response.status, data, text, headers: response.headers };};async function start() {server = spawn(BIN, ['project.hl'], { cwd: APP, env });console.log('PROCESS tickets', server.pid); server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);for (const end=Date.now()+120000; Date.now()<end;) { try { if ((await api('/api/projects')).status === 200) return; } catch {} await sleep(200); }throw Error('server did not start: '+log);}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'); } }const sub = (id, suffix='delta') => '/api/subscriptions/' + id + '/' + suffix;const comment = (text, token=K.bobToken) => api('/api/projects/alpha/tickets/1/comments', 'POST', {text}, token);try {const kat = spawnSync(BIN, ['tests/subscriptions-hmac.hl'], { cwd: APP, env, encoding: 'utf8', timeout:120000 });check('HMAC known answer', kat.stdout.trim() === 'sha256=f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8', kat.stdout+kat.stderr);await start();check('no token refused', (await api('/api/subscriptions','GET',undefined,null)).status===401);check('project key refused', (await api('/api/subscriptions','GET',undefined,K.betaKey)).status===401);let r=await api('/api/subscriptions','POST',{projects:[K.alpha],owner:K.carol},K.bobToken);check('nonadmin for another user refused',r.status===403,r);r=await api('/api/subscriptions','POST',{projects:'all',owner:K.bob}); check('all for another user refused',r.status===403,r);r=await api('/api/subscriptions','POST',{projects:[K.alpha],owner:K.bob,label:'bob alpha'});check('admin subscribes another user',r.status===201,r);const other=r.data?.subscription?.id;r=await api('/api/subscriptions','POST',{projects:[K.alpha],label:'alice alpha'});check('create self baseline',r.status===201 && r.data.subscription.cursor>=2,r);const id=r.data?.subscription?.id;check('list own and administered', (await api('/api/subscriptions')).data.subscriptions.length===2);check('other cannot fetch', (await api(sub(id),'GET',undefined,K.bobToken)).status===403);check('other cannot remove', (await api(sub(id,'remove'),'POST',{},K.bobToken)).status===403);check('baseline empty', (await api(sub(id))).data.tickets.length===0);await comment('self only',K.aliceToken); await sleep(250);check('own events absent', (await api(sub(id)+'?peek=1')).data.tickets.length===0);check('own events never wake own subscription', wakes.every(w=>w.body.subscription!==id));check('comment write succeeds',(await comment('hello alice')).status===201);await sleep(300);const first=wakes.filter(w=>w.body.subscription===id);check('one signed content-free wake', first.length===1 && first[0].valid && Object.keys(first[0].body).sort().join() === 'at,delivery,subscription',first);await comment('second alice'); await sleep(300);check('no further wakes pending',wakes.filter(w=>w.body.subscription===id).length===1);for (const state of ['review','done']) await api('/api/projects/alpha/tickets/1/state','POST',{state},K.aliceToken);// bob has use role; temporarily promote so he can generate both state events, while self exclusion stays mandatory.await api('/api/projects/alpha/members','POST',{user:K.bob,role:'edit'});await api('/api/projects/alpha/tickets/1/state','POST',{state:'open'},K.bobToken);await api('/api/projects/alpha/tickets/1/state','POST',{state:'review'},K.bobToken);await api('/api/projects/alpha/tickets/1/state','POST',{state:'done'},K.bobToken);await api('/api/projects/alpha/tickets/1/assign','POST',{assignee:K.bob},K.bobToken);await api('/api/projects/alpha/tickets/1/assign','POST',{assignee:K.alice},K.bobToken);await api('/api/projects/alpha/tickets/1/edit','POST',{subject:'edited',summary:'alice summary'},K.bobToken);await api('/api/projects/alpha/tickets/1/blocked-by','POST',{add:'beta#1'},K.bobToken);r=await api(sub(id)+'?peek=1'); const t=r.data.tickets[0];check('merged per ticket',r.data.tickets.length===1 && t.changes.state.from==='done' && t.changes.state.to==='done',r.data);check('comments and full last snippet',t.changes.comments===2 && t.changes.lastComment==='second alice',t);check('all relevance markers', ['assigned','own','mention'].every(x=>t.relevance.includes(x)),t);check('edit, assignment and links', t.changes.titleEdited && t.changes.summaryEdited && t.changes.assignee.to===K.alice && t.changes.links.length===1,t);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);check('peek keeps pending',(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakePending);r=await api(sub(id),'GET',undefined,K.aliceToken,true);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);check('fetch drains', (await api(sub(id))).data.tickets.length===0);check('fetch clears wakePending',!(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===id).wakePending);await comment('after fetch'); await sleep(300);check('new episode wakes',wakes.filter(w=>w.body.subscription===id).length===2);await stop(); await start(); await sleep(400);const restarted=wakes.filter(w=>w.body.subscription===id);check('restart rewakes same delivery',restarted.length===3 && restarted[1].body.delivery===restarted[2].body.delivery,restarted);await api(sub(id));// Lots of tickets exercise byte cap and project overflow, all from non-owner bob.for (let i=0;i<35;i++) await api('/api/projects/alpha/tickets','POST',{subject:'bulk '+i+' '+ '界'.repeat(60),summary:'bulk'},K.bobToken);r=await api(sub(id)+'?peek=1','GET',undefined,K.aliceToken,true);check('Markdown UTF-8 cap and summary',Buffer.byteLength(r.text)<=4096 && /… and \d+ more tickets in alpha \(\d+\)/.test(r.text),r.text);check('JSON retains overflow', (await api(sub(id)+'?peek=1')).data.tickets.length===35);r=await api(sub(other,'remove'),'POST',{}); check('admin removes',r.status===200,r);r=await api(sub(id,'remove'),'POST',{}); check('owner removes',r.status===200,r);check('removed route 404',(await api(sub(id))).status===404);r=await api('/api/subscriptions','POST',{projects:'all'},K.carolToken); const overview=r.data.subscription.id;await comment('overview alpha');await api('/api/projects/beta/tickets/1/comments','POST',{text:'overview beta'},K.bobToken);r=await api(sub(overview),'GET',undefined,K.carolToken);check('all-project self overview coalesces both projects',r.data.tickets.length===2 && r.data.tickets.some(t=>t.project==='alpha') && r.data.tickets.some(t=>t.project==='beta'),r.data);await api(sub(overview,'remove'),'POST',{},K.carolToken);// Main/standby overlap: only main may send; a disabled standby writes to the same numbered store.const standby = spawn(BIN, ['project.hl'], {cwd: APP, env: {...env,TICKETS_PORT:'8752',TICKETS_WAKES_DISABLED:'1'}});console.log('PROCESS standby',standby.pid);standby.stdout.on('data',d=>log+=d); standby.stderr.on('data',d=>log+=d);try {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);}r=await api('/api/subscriptions','POST',{projects:[K.alpha]}); const pending=r.data.subscription.id;const mark=wakes.length;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'})});await sleep(1600);check('standby write gets one main wake',wakes.slice(mark).filter(w=>w.body.subscription===pending).length===1,wakes.slice(mark));await api(sub(pending,'remove'),'POST',{});} finally { standby.kill('SIGTERM'); await Promise.race([new Promise(r=>standby.once('exit',r)),sleep(3000)]); if(standby.exitCode===null)standby.kill('SIGKILL'); }// Create one rejected episode, then exercise actual HTTP retries with test-only due-time advancement.reject=true;r=await api('/api/subscriptions','POST',{projects:[K.alpha]}); const failing=r.data.subscription.id;await comment('retry me'); await sleep(300); await stop();const retryMark=wakes.length;const retry=spawn(BIN,['tests/subscriptions-retry.hl'],{cwd:APP,env}); console.log('PROCESS retries',retry.pid);let retryLog=''; retry.stdout.on('data',d=>retryLog+=d);retry.stderr.on('data',d=>retryLog+=d);let retryTimeout;const done=await Promise.race([new Promise(r=>retry.once('exit',r)),new Promise(r=>{retryTimeout=setTimeout(()=>r('timeout'),120000);})]);clearTimeout(retryTimeout);if(done==='timeout')retry.kill('SIGKILL');check('failed wake retries then failed after five attempts',done===0 && /FAILED_AFTER 5/.test(retryLog) && wakes.length-retryMark===5,retryLog);const delays=[...retryLog.matchAll(/RETRY (\d+) DELAY ([\d.]+)/g)].map(m=>Number(m[2]));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);reject=false; await start(); await sleep(300);check('restart recovers failed undelivered subscription',(await api('/api/subscriptions')).data.subscriptions.find(s=>s.id===failing).wakeStatus==='sent');await api(sub(failing,'remove'),'POST',{});} catch(e) { check('suite completed',false,e.stack); }finally { await stop(); await new Promise(r=>fake.close(r)); writeFileSync(join(STORE,'server.log'),log); }console.log(`${passed} passed, ${failed} failed`); process.exitCode=failed?1:0;
Branches
Latest commits
- d662ad27Remove superseded waker service for direct chat push protocolmre
- ff2e8701Finalize subscription build verification and handoff reportmre
- 54bc5fe1Harden delta relevance, overflow caps and retry verificationmre
- 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