gitoria
All repositories: gitoria
10.8 KB
import { requiredPort } from './gate-ports.mjs';// tests/status-keyed.mjs — GATE OF gitoria#46 / contract v1.4 (statuses keyed by app + context). Real HTTP, real git, and the OLD code (the commit before the change, 9678a8f,// taken with `git archive`) on the SAME storage: a status row written in the OLD shape (one row per sha + context, key without the app id) must still be read after the// new code starts, and must be replaced correctly by the SAME app's next PUT (no one-off script, no migration); another app on the same context gets its own row.// node tests/status-keyed.mjs (GITORIA_KEYED_PORT required, GITORIA_KEYED_IDENT_PORT required)import { spawn, execFileSync } from 'node:child_process';import { request } from 'node:http';import { mkdirSync, rmSync, writeFileSync, existsSync } from 'node:fs';import { dirname, join, resolve } from 'node:path';import { fileURLToPath } from 'node:url';import { startIdent } from './identkit.mjs';const HERE = dirname(fileURLToPath(import.meta.url));const APP = resolve(HERE, '..');const PORT = requiredPort('GITORIA_KEYED_PORT'), IDENT_PORT = requiredPort('GITORIA_KEYED_IDENT_PORT');const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || [resolve(APP, '../ident.worldapi.org'), '/media/STORAGE/projects/WorldAPI/ident.worldapi.org'].find(d => existsSync(join(d, 'project.hl')));const STORE = join(APP, '.scratch/keyed-store');const LIFE = 600000; // Mint once; allow two cold starts (each may take up to 240 s).const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));let passes = 0, failures = 0;const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };function raw(method, path, { host = `localhost:${PORT}`, headers = {}, body = null, cookie = null } = {}) {return new Promise((res, rej) => {const h = { host, ...headers }; if (cookie) h.cookie = cookie;if (body !== null) h['content-length'] = Buffer.byteLength(body);const r = request({ host: '127.0.0.1', port: PORT, method, path, headers: h }, (m) => { const c = []; m.on('data', d => c.push(d)); m.on('end', () => res({ status: m.statusCode, headers: m.headers, body: Buffer.concat(c).toString('utf8') })); });r.on('error', rej); if (body !== null) r.write(body); r.end();});}const get = (path, o = {}) => raw('GET', path, o);const at = (label, path, method = 'GET', o = {}) => raw(method, path, { host: `${label}.localhost:${PORT}`, ...o });const errCode = (r) => { try { return JSON.parse(r.body).error.code; } catch { return null; } };let server = null, log = '';function startServer(env, dir = APP) {log = '';const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: `http://localhost:${PORT}`, GITORIA_SSH_SECRET: 'sshsecret-status-gate', GITORIA_TICKETS_URL: 'http://127.0.0.1:1', GITORIA_APP_TOKEN_LIFE_MS: String(LIFE), ...env } });p.stdout.on('data', d => log += d); p.stderr.on('data', d => log += d);server = p; return p;}async function up() { for (let i = 0; i < 960; i++) { try { if ((await get('/api/repos')).status === 200) return; } catch {} await sleep(250); } throw new Error('gitoria did not come up\n' + log); }const stop = async () => { if (server) { const p = server; server = null; p.kill(); await new Promise(r => p.once('exit', r)); } };let ident;try {rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });const OLD = join(STORE, 'oldapp'); mkdirSync(OLD, { recursive: true });execFileSync('sh', ['-c', `git -C '${APP}' archive 9678a8f | tar -x -C '${OLD}' && ln -s '${join(APP, 'bin')}' '${OLD}/bin'; true`]);ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });const alice = await ident.signIn('[email protected]');const BASE = `http://localhost:${PORT}`;const app = await ident.registerApp(alice, 'gitoria (status gate)', [BASE]);const ENV = { GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: join(STORE, 'git'), IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret };startServer(ENV, OLD); await up();const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;const ck0 = cookieOf(await get('/'));const cb = await get('/login/callback?ident_code=' + await ident.selectorCode(alice, app, BASE) + '&next=%2F', { cookie: ck0 });const A = { cookie: cookieOf(cb) || ck0 };let n = 0;const face = async (event, payload, cookie = A.cookie) => {const r = await raw('POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie, body: J({ t: 'emit', i: ++n, event, payload }) });let j = null; try { j = JSON.parse(r.body); } catch {}return j && j.value;};await face('gitoriaSaveName', ['Alice']);const tA = (await face('gitoriaMakeToken', ['a'])).token;const W = join(STORE, 'work'); mkdirSync(W, { recursive: true });const genv = { ...process.env, GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_GLOBAL: '/dev/null', GIT_AUTHOR_NAME: 'a', GIT_AUTHOR_EMAIL: 'a@a', GIT_COMMITTER_NAME: 'a', GIT_COMMITTER_EMAIL: 'a@a' };const g = (...a) => execFileSync('git', a, { cwd: W, encoding: 'utf8', env: genv, stdio: ['ignore', 'pipe', 'pipe'] });const sh = (fn) => { try { return fn(); } catch (e) { return null; } };const urlOf = (host, path) => `http://a:${tA}@${host}.localhost:${PORT}/${path}`;const push = (host, path, ...refs) => sh(() => { g('push', '-q', urlOf(host, path), ...refs); return true; });const sha = () => g('rev-parse', 'HEAD').trim();g('init', '-q', '-b', 'main'); writeFileSync(join(W, 'README.md'), '# t\n'); g('add', '-A'); g('commit', '-q', '-m', 'init');const mainSha = sha();check('alice creates "pub" and "other"', !!(await face('gitoriaCreate', ['pub', 'p'])).repo && !!(await face('gitoriaCreate', ['other', 'o'])).repo);check('alice pushes main to pub and to other', push('pub', 'pub.git', 'main') === true && push('other', 'other.git', 'main') === true);// a pull request on pub: branch feat with a |||PR commitg('checkout', '-q', '-b', 'feat'); writeFileSync(join(W, 'a.txt'), 'a\n'); g('add', '-A'); g('commit', '-q', '-m', '|||PR Add a');const prCommit = sha(), h1 = sha();check('alice pushes the branch feat with a |||PR commit', push('pub', 'pub.git', 'feat') === true);g('checkout', '-q', 'main'); g('checkout', '-q', '-b', 'lone'); writeFileSync(join(W, 'o.txt'), 'o\n'); g('add', '-A'); g('commit', '-q', '-m', 'only on other');const otherSha = sha();check('a commit that exists only in the repo "other"', push('other', 'other.git', 'lone') === true);// the OLD code is the one in OLD (commit 9678a8f), the NEW code is this tree; both on ENV's storageconst addApp = (slug, name) => face('gitoriaAppAdd', [slug, name, 'https://kunibert.worldapi.org/hook']);const idOf = (r, name) => ((r.rows || []).find(x => x.name === name) || {}).id;const H = (host) => `${host}.localhost:${PORT}`;const tok = async (host, key) => JSON.parse((await raw('POST', '/api/apps/token', { host: H(host), headers: { authorization: 'Bearer ' + key } })).body).token;const put = (token, shaArg, body) => raw('PUT', '/api/statuses/' + shaArg, { host: H('pub'), headers: { authorization: 'Bearer ' + token, 'content-type': 'application/json' }, body: J(body) });const list = async (token) => JSON.parse((await raw('GET', '/api/statuses/' + h1, { host: H('pub'), headers: { authorization: 'Bearer ' + token } })).body).statuses;const st = (context, state, title) => ({ context, state, title, summary: '', url: null });const kK = await addApp('pub', 'Kunibert'); const kM = await addApp('pub', 'Mallory');const tK = await tok('pub', kK.key), tM = await tok('pub', kM.key);check('(old code) apps added', !!tK && !!tM);// ---- the OLD code writes the old shape ----check('(old code) Kunibert sets kunibert=success', (await put(tK, h1, st('kunibert', 'success', 'old row'))).status === 200);check('(old code, the bug) Mallory\'s PUT replaces it: one row, app Mallory', await (async () => { const r = await put(tM, h1, st('kunibert', 'failure', 'fake')); const l = (JSON.parse(r.body).status) ; return r.status === 200 && l.app.name === 'Mallory'; })());check('(old code) Kunibert sets it again (old key: sha + context)', await (async () => { await put(tK, h1, st('kunibert', 'success', 'old row')); return true; })());await stop();// ---- the NEW code on the same storage ----startServer(ENV, APP); await up();check('(new index) context suggestion reads the existing old-shape status', (await face('gitoriaAppContext', ['pub', idOf(kK, 'Kunibert')]))?.context === 'kunibert');let l = await list(tK);check('(new code) the old-shape row is read: ONE kunibert status, app Kunibert, success, title "old row"', l.length === 1 && l[0].app.name === 'Kunibert' && l[0].state === 'success' && l[0].title === 'old row', J(l));check('(new code) pull.statuses shows it too', await (async () => { const p = JSON.parse((await raw('GET', '/api/pulls/1', { host: H('pub'), headers: { authorization: 'Bearer ' + tK } })).body); return p.statuses.length === 1 && p.statuses[0].app.name === 'Kunibert' && Array.isArray(p.required) && p.required.length === 0; })());check('(new code) Mallory sets the same context: gets her OWN row, Kunibert\'s old row is untouched', (await put(tM, h1, st('kunibert', 'failure', 'mal'))).status === 200 && await (async () => { l = await list(tK); return l.length === 2 && l.find(x => x.app.name === 'Kunibert').state === 'success' && l.find(x => x.app.name === 'Kunibert').title === 'old row' && l.find(x => x.app.name === 'Mallory').state === 'failure'; })(), J(l));check('(new code) Kunibert\'s next PUT REPLACES its old-shape row (still two rows, not three): now failure, title "new"', (await put(tK, h1, st('kunibert', 'failure', 'new'))).status === 200 && await (async () => { l = await list(tK); const k = l.filter(x => x.app.name === 'Kunibert'); return l.length === 2 && k.length === 1 && k[0].state === 'failure' && k[0].title === 'new' && l.find(x => x.app.name === 'Mallory').title === 'mal'; })(), J(l));await put(tK, h1, st('kunibert', 'success', 'again'));await stop(); startServer(ENV, APP); await up();l = await list(tK);check('(new code, after another restart) two rows, Kunibert success "again", Mallory failure "mal"', l.length === 2 && l.find(x => x.app.name === 'Kunibert').title === 'again' && l.find(x => x.app.name === 'Mallory').title === 'mal', J(l));} catch (e) {check('the gate ran without an exception', false, String(e && e.stack || e));} finally {await stop().catch(() => {});try { ident && ident.stop && await ident.stop(); } catch {}console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);}
Branches
Latest commits
- fe209ffeMerge branch 'w56-owner-members' into mainGitoria
- fa0754c8|||PR repository owner transfer and members API (#55)mre
- 8862e537Merge branch 'w55-rename-org' into mainGitoria
- 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
- 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
- 499f25f2Review fixes for the Settings organization move (#53)mre
- ed3b922b|||PR move a repository into an organization in Settings (#53)mre
- 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
- 9f7ce8d8Preserve rename compatibility and live page titlesmre
- c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
- ce08920dMerge branch 'w52c-header-phone' into mainGitoria
- 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre
- e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
- c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
- 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
- 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
- 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
- 155861f6Merge branch 'w52-person-approval' into mainGitoria
- b5435de8|||PR person approvals: second Kunibert round (#52)mre
- 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre