tickets
All repositories: gitoria
10.4 KB
// tests/purge94.mjs — mission 028 (#94, identity rule): the one-time purge on a FIXTURE copy (fake project miserit-anthar, never real data).// usage: node tests/purge94.mjs <fixtureDir with base/ and seed.json> <workDir> <oldTree> <newTree> <portA> <portB>// Runs the SAME checks twice: on the old tree (they must FAIL there) and on the new one (must pass). Prints counts and ids only, never a text.import { execFileSync, spawn } from 'node:child_process';import { cpSync, readFileSync, writeFileSync, mkdirSync, rmSync, readdirSync, statSync } from 'node:fs';import { createHash } from 'node:crypto';import { join } from 'node:path';const [FX, WORK, OLD, NEW, PA, PB] = process.argv.slice(2);const seed = JSON.parse(readFileSync(join(FX, 'seed.json'), 'utf8').replace(/^SEED /, ''));const pids = [];let fails = 0, passes = 0;const check = (label, ok, extra = '') => { ok ? passes++ : fails++; console.log((ok ? ' ok ' : ' FAIL ') + label + (extra ? ' — ' + extra : '')); };function env(dir, port) {return { ...process.env, TICKETS_PORT: String(port), TICKETS_STORAGE: dir + '/storage/mpackdb', TICKETS_ATTACHMENTS: dir + '/storage/attachments',TICKETS_SESSIONS: dir + '/sessions', IDENT_URL: 'http://127.0.0.1:9', IDENT_EXCHANGE_URL: 'http://127.0.0.1:9', TICKETS_PUBLIC_URL: 'http://127.0.0.1:' + port,TICKETS_CREATOR_IDENTITY: '', TICKETS_WATCH: '0', TICKETS_WAKES_DISABLED: '1', IDENT_API_KEY: 'pk_p94', IDENT_API_SECRET: '' };}async function start(tree, dir, port) {mkdirSync(dir + '/sessions', { recursive: true });const p = spawn(tree + '/bin/hybriel', ['project.hl'], { cwd: tree, env: env(dir, port), stdio: ['ignore', 'pipe', 'pipe'], detached: false });pids.push(p.pid);let log = ''; p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);for (let i = 0; i < 240; i++) {try { const r = await fetch(`http://127.0.0.1:${port}/api/projects/other-proj/tickets/1`); if (r.status === 200) return { p, log: () => log }; } catch {}await new Promise(r => setTimeout(r, 1000));}throw new Error('server did not start');}async function stop(s) { s.p.kill('SIGTERM'); await new Promise(r => { s.p.on('exit', r); setTimeout(r, 15000); }); }const counts = (tree, dir) => JSON.parse(execFileSync(tree + '/bin/hybriel', ['tests/purge94-count.hl', seed.t94], { cwd: NEW, env: env(dir, 1) }).toString().split('COUNTS ')[1]);function filesOf(dir) { const out = {}; const walk = d => { for (const n of readdirSync(d)) { const p = join(d, n); const s = statSync(p); if (s.isDirectory()) walk(p); else out[p.slice(dir.length)] = { mtime: s.mtimeMs, sha: createHash('sha1').update(readFileSync(p)).digest('hex') }; } }; walk(dir + '/storage'); return out; }function grepHits(dir, needle) { let n = 0; const walk = d => { for (const f of readdirSync(d)) { const p = join(d, f); if (statSync(p).isDirectory()) walk(p); else if (readFileSync(p).includes(needle)) n++; } }; walk(dir + '/storage'); return n; }async function getAll(port, withNames) {const H = { authorization: 'Bearer ' + seed.token };const base = `http://127.0.0.1:${port}`;const out = { tickets: {}, status: {} };for (let n = 1; n <= 94; n++) { const r = await fetch(`${base}/api/projects/miserit-anthar/tickets/${n}`, { headers: H }); out.status[n] = r.status; out.tickets[n] = await r.text(); }const get = async (path, h = H) => { const r = await fetch(base + path, { headers: h }); return { status: r.status, text: await r.text() }; };const p94 = await get('/miserit-anthar/94'), p999 = await get('/miserit-anthar/999');out.page94 = /fixture ticket 94|first comment|second comment/.test(p94.text) || p94.text.includes(seed.t94) ? 'shows the ticket' : p94.text.includes('no such ticket') && p999.text.includes('no such ticket') ? 'the no-such-ticket page, as for a number that never existed' : 'other: ' + p94.status;out.md94 = (await get('/api/projects/miserit-anthar/tickets/94', { ...H, accept: 'text/markdown' })).status;out.list = (await get('/api/projects/miserit-anthar/tickets')).text;out.other = (await get('/api/projects/other-proj/tickets/1')).text;out.delta = (await get(`/api/subscriptions/${seed.sub}/delta?peek=1`)).text;out.deltaMd = (await get(`/api/subscriptions/${seed.sub}/delta?peek=1`, { ...H, accept: 'text/markdown' })).text;const ctl = new AbortController(); const t = setTimeout(() => ctl.abort(), 4000);let sse = ''; try { const r = await fetch(`${base}/api/events?after=0`, { headers: H, signal: ctl.signal }); const rd = r.body.getReader(); const dec = new TextDecoder(); for (;;) { const { value, done } = await rd.read(); if (done) break; sse += dec.decode(value); } } catch {}clearTimeout(t); out.sse = sse;return out;}async function run(label, tree, port) {console.log(`\n== ${label} (${tree}) ==`);const dir = join(WORK, label); rmSync(dir, { recursive: true, force: true }); mkdirSync(dir, { recursive: true });cpSync(join(FX, 'base', 'storage'), dir + '/storage', { recursive: true });const before = counts(tree, dir);console.log('before counts', JSON.stringify(before));const grepBefore = grepHits(dir, seed.t94);const s1 = await start(tree, dir, port);const api = await getAll(port, false);const mig = s1.log().split('\n').filter(l => l.includes('migrated:'));await stop(s1);const after = counts(tree, dir);console.log('after counts ', JSON.stringify(after));console.log('migration log lines:', JSON.stringify(mig));const grepAfter = grepHits(dir, seed.t94);const f1 = filesOf(dir);await new Promise(r => setTimeout(r, 1100));const s2 = await start(tree, dir, port);const nextNo = await (async () => { // a new ticket takes the next numberconst r = await fetch(`http://127.0.0.1:${port}/api/projects/miserit-anthar/tickets`, { method: 'POST', headers: { authorization: 'Bearer ' + seed.token, 'content-type': 'application/json' }, body: JSON.stringify({ subject: 'fixture new', summary: 'x' }) });return (await r.json()).ticket?.number; })();await stop(s2);// second start rewrote nothing: compare BEFORE the new ticket was written -> redo on a fresh copy of f1 state is not needed; use a third start belowconst dir3 = dir; // third start with no writes by usconst f2pre = filesOf(dir3);await new Promise(r => setTimeout(r, 1100));const s3 = await start(tree, dir, port); await stop(s3);const f3 = filesOf(dir);const rewritten = Object.keys(f3).filter(k => !f2pre[k] || f2pre[k].sha !== f3[k].sha || f2pre[k].mtime !== f3[k].mtime);return { before, after, grepBefore, grepAfter, api, nextNo, rewritten, mig, f1 };}mkdirSync(WORK, { recursive: true });const oldR = await run('old', OLD, PA);const newR = await run('new', NEW, PB);for (const [label, R] of [['OLD code (checks must FAIL here)', oldR], ['NEW code', newR]]) {console.log(`\n-- checks on ${label} --`);const A = R.after;check('#94 counts: tickets 1→0', A.tickets === 0, `tickets ${R.before.tickets}→${A.tickets}`);check('events >0→0', R.before.events > 0 && A.events === 0, `${R.before.events}→${A.events}`);check('stream rows >0→0', R.before.stream > 0 && A.stream === 0, `${R.before.stream}→${A.stream}`);check('comment changes >0→0', R.before.commentChanges > 0 && A.commentChanges === 0, `${R.before.commentChanges}→${A.commentChanges}`);check('comment likes >0→0', R.before.commentLikes > 0 && A.commentLikes === 0, `${R.before.commentLikes}→${A.commentLikes}`);check('attachments rows >0→0', R.before.attachments > 0 && A.attachments === 0, `${R.before.attachments}→${A.attachments}`);check('attachment files on disk >0→0', R.before.attachmentFiles > 0 && A.attachmentFiles === 0, `${R.before.attachmentFiles}→${A.attachmentFiles}`);check('relation rows >0→0', R.before.links > 0 && A.links === 0, `${R.before.links}→${A.links}`);check('link events of other tickets >0→0', R.before.linkEventsOfOthers > 0 && A.linkEventsOfOthers === 0, `${R.before.linkEventsOfOthers}→${A.linkEventsOfOthers}`);check('stream total unchanged (the counter stays whole)', A.streamTotal === R.before.streamTotal, `${R.before.streamTotal}→${A.streamTotal}`);check('API ticket #94 answers 404', R.api.status[94] === 404, 'status ' + R.api.status[94]);check('page /miserit-anthar/94 is the "no such ticket" page, no trace of #94', R.api.page94.startsWith('the no-such-ticket page'), R.api.page94);check('Markdown #94 answers 404', R.api.md94 === 404, 'status ' + R.api.md94);check('/api/events replay holds no trace of its ticket id', !R.api.sse.includes(seed.t94) && R.api.sse.length > 0, 'bytes ' + R.api.sse.length);check('delta holds no trace of #94 (ref or id)', !R.api.delta.includes(seed.t94) && !R.api.delta.includes('#94') && !R.api.deltaMd.includes('#94') && R.api.delta.includes('"tickets"'), 'delta bytes ' + R.api.delta.length);check('file grep for #94 ticket id: 0 hits', R.grepAfter === 0, `files with the id ${R.grepBefore}→${R.grepAfter}`);check('new ticket numbered 95', R.nextNo === 95, 'got ' + R.nextNo);check('a further start rewrites no file', R.rewritten.length === 0, 'rewritten ' + JSON.stringify(R.rewritten));}// other tickets byte-identical old vs new (the old run is the "before")const differ = [];for (let n = 1; n <= 93; n++) if (oldR.api.tickets[n] !== newR.api.tickets[n]) differ.push(n);console.log('\n-- other tickets, API JSON before (old code) vs after (new code) --');console.log('differing tickets (expected: only those with a relation to #94):', JSON.stringify(differ));check('differing tickets are exactly #10, #30, #50, #93 (they held a relation to #94)', JSON.stringify(differ) === JSON.stringify([10, 30, 50, 93]));check('every other ticket (89 of 93) byte-identical', 93 - differ.length === 89);check('other project ticket byte-identical', oldR.api.other === newR.api.other);// what changed in those three: only the relation fields and the events list shrankfor (const n of differ) {const o = JSON.parse(oldR.api.tickets[n]), w = JSON.parse(newR.api.tickets[n]);const keys = new Set([...Object.keys(o.ticket), ...Object.keys(w.ticket)]);const dk = [...keys].filter(k => JSON.stringify(o.ticket[k]) !== JSON.stringify(w.ticket[k]));console.log(` #${n}: changed ticket fields ${JSON.stringify(dk)}; events ${o.events.length}→${w.events.length}`);}console.log(`\nRESULT: ${passes} passed, ${fails} failed (checks run on both trees; the OLD tree is expected to fail the purge checks)`);for (const p of pids) { try { process.kill(p, 0); console.log('still running', p); } catch {} }console.log('started PIDs (all stopped):', pids.join(' '));
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