gitoria
All repositories: gitoria
10.9 KB
// tests/readme-cache.mjs — THE README CACHE GATE (gitoria#25): a repeat request for a repo's README must not read git again// (the homepage is kept per commit), and a push must show the new README at once. A shim `git` in front of the real one logs// every call the server makes, so the gate counts git calls: a request that is served from the cache runs for-each-ref only// (that call gives the commit id); a built one also runs ls-tree and cat-file. The HTML of the cached answer must be byte// for byte the one that was built. Real HTTP against a real local gitoria + its own ident (tests/identkit.mjs), the REAL git// binary for the pushes (into the bare repository on disk).// node tests/readme-cache.mjs (GITORIA_RC_PORT, else GITORIA_SEC_PORT, default 8916; GITORIA_RC_IDENT_PORT, else GITORIA_SEC_IDENT_PORT, default 8917: the gates run one after the other)import { spawn, execFileSync } from 'node:child_process';import { request } from 'node:http';import { mkdirSync, rmSync, writeFileSync, readFileSync, existsSync, chmodSync } 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 = Number(process.env.GITORIA_RC_PORT || process.env.GITORIA_SEC_PORT || 8916), IDENT_PORT = Number(process.env.GITORIA_RC_IDENT_PORT || process.env.GITORIA_SEC_IDENT_PORT || 8917);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/rc-store');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(port, 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, 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('latin1') })); });r.on('error', rej); if (body !== null) r.write(body); r.end();});}const get = (path, o = {}) => raw(PORT, 'GET', path, o);const sleepUp = async (srv) => {for (let i = 0; i < 960; i++) { try { if ((await raw(PORT, 'GET', '/api/repos')).status === 200) return; } catch {} await sleep(250); }throw new Error('gitoria did not come up\n' + srv.log());};const procs = [];let ident;try {rmSync(STORE, { recursive: true, force: true }); mkdirSync(join(STORE, 'shim'), { recursive: true });const LOG = join(STORE, 'git-calls.log');writeFileSync(join(STORE, 'shim/git'), `#!/bin/sh\necho "$@" >> "${LOG}"\nexec /usr/bin/git "$@"\n`); chmodSync(join(STORE, 'shim/git'), 0o755);writeFileSync(LOG, '');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 (readme cache gate)', [BASE]);let slog = '';const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],env: { ...process.env, PATH: join(STORE, 'shim') + ':' + process.env.PATH, GITORIA_PORT: String(PORT), GITORIA_WATCH: '0', GITORIA_PUBLIC_URL: BASE, GITORIA_TICKETS_URL: 'http://127.0.0.1:1',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 } });p.stdout.on('data', d => slog += d); p.stderr.on('data', d => slog += d); procs.push(p);await sleepUp({ log: () => slog });const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;const ck0 = cookieOf(await get('/'));const code = await ident.selectorCode(alice, app, BASE);const cb = await get('/login/callback?ident_code=' + code + '&next=%2F', { cookie: ck0 });const A = { cookie: cookieOf(cb) || ck0 };let n = 0;const face = async (who, event, payload) => {const r = await raw(PORT, 'POST', '/__hl/emit', { headers: { 'content-type': 'application/json' }, cookie: who && who.cookie, body: J({ t: 'emit', i: ++n, event, payload }) });let j = null; try { j = JSON.parse(r.body); } catch {}return { status: r.status, value: j && j.value, error: j && j.error };};await face(A, 'gitoriaSaveName', ['Alice']);const mk = await face(A, 'gitoriaCreate', ['alpha', 'cache gate repo']);check('the gate repo is created', !!(mk.value && mk.value.repo && mk.value.repo.slug === 'alpha'), J(mk.value));// push a README into the bare repository on disk with the real git binaryconst bare = join(STORE, 'git', 'alpha.git'), work = join(STORE, 'work');const g = (cwd, ...a) => execFileSync('/usr/bin/git', ['-c', 'user.name=Gate', '-c', '[email protected]', ...a], { cwd, stdio: 'pipe' }).toString();mkdirSync(work, { recursive: true }); g(work, 'init', '-q', '-b', 'main');const push = (text) => { writeFileSync(join(work, 'README.md'), text); g(work, 'add', '.'); g(work, 'commit', '-q', '-m', 'readme'); g(work, 'push', '-q', bare, 'HEAD:refs/heads/main'); };const calls = () => { const t = readFileSync(LOG, 'utf8'); writeFileSync(LOG, ''); return t.split('\n').filter(Boolean); };const has = (cs, sub) => cs.some(c => c.includes(' ' + sub));// The page key (lib/pagekey.hl) reads the branches with one for-each-ref. Building the page runs homepageNow, which reads them// once more. So one for-each-ref in a request means the finished page was served without building it (gitoria#25, W149).const refReads = (cs) => cs.filter(c => c.includes(' for-each-ref')).length;const page = () => get('/', { host: `alpha.localhost:${PORT}` });const body = (r) => r.body.replace(/"at":\d+/g, '"at":T');push('# First title\n\nthe first README text FIRSTMARK\n');calls();const r1 = await page(); const c1 = calls();check('first README request shows the README', r1.status === 200 && r1.body.includes('FIRSTMARK'), `status ${r1.status}`);check('first request reads git for the tree and the file (built)', has(c1, 'ls-tree') && has(c1, 'cat-file'), J(c1));const r2 = await page(); const c2 = calls();check('a repeat request shows the same README', r2.status === 200 && r2.body.includes('FIRSTMARK'));check('a repeat request is served from the cache: no ls-tree, no cat-file', !has(c2, 'ls-tree') && !has(c2, 'cat-file'), J(c2));check('the cached HTML is byte for byte the built HTML', body(r1) === body(r2), `${r1.body.length} vs ${r2.body.length} bytes`);const r3 = await page(); const c3 = calls();check('a third request is still served from the cache', !has(c3, 'ls-tree') && !has(c3, 'cat-file') && body(r3) === body(r1), J(c3));push('# Second title\n\nthe second README text SECONDMARK\n');calls();const r4 = await page(); const c4 = calls();check('after a push the new README shows at once', r4.status === 200 && r4.body.includes('SECONDMARK') && !r4.body.includes('FIRSTMARK'), 'old README still served');check('after a push the homepage is built again', has(c4, 'ls-tree') && has(c4, 'cat-file'), J(c4));const r5 = await page(); const c5 = calls();check('and the new README is cached in turn', r5.body.includes('SECONDMARK') && !has(c5, 'ls-tree') && body(r5) === body(r4), J(c5));// W149 / gitoria#25: the finished page is served again without building itcheck('the first request built the page: the branches were read twice (key + homepage)', refReads(c1) === 2, J(c1));check('a repeat request does not build the page: the branches were read once (the key only)', refReads(c2) === 1 && refReads(c3) === 1, J([c2, c3]));check('after a push the page is built again, then served kept', refReads(c4) === 2 && refReads(c5) === 1, J([c4, c5]));// three visitors: signed in as Alice, signed in as Bob, signed out. Each gets the shell of their own session.const bobU = await ident.signIn('[email protected]');const bcode = await ident.selectorCode(bobU, app, BASE);const bck0 = cookieOf(await get('/'));const bcb = await get('/login/callback?ident_code=' + bcode + '&next=%2F', { cookie: bck0 });const B = { cookie: cookieOf(bcb) || bck0 };await face(B, 'gitoriaSaveName', ['Bobby']);const visit = (who) => get('/', { host: `alpha.localhost:${PORT}`, cookie: who && who.cookie });const seq = [];for (let round = 0; round < 3; round++) for (const [name, who] of [['alice', A], ['bob', B], ['out', null]]) { calls(); const r = await visit(who); seq.push({ name, round, body: body(r).replace(/hlsid=[0-9a-f]+/g, ''), reads: refReads(calls()) }); }const of = (name, round) => seq.find(x => x.name === name && x.round === round);// the shell carries the visitor: the signed-in user's id is in the page, and the page of anyone else does not have itconst idIn = (b) => (/"session":\{"user":\{"id":"([^"]+)"/.exec(b) || [])[1] || null;const idA = idIn(of('alice', 0).body), idB = idIn(of('bob', 0).body);check('Alice and Bob each get a signed-in shell with an id of their own, the signed-out visitor has none', !!idA && !!idB && idA !== idB && idIn(of('out', 0).body) === null, J([idA, idB, idIn(of('out', 0).body)]));check('no page carries the id of another visitor', ['alice', 'bob', 'out'].every(n => [0, 1, 2].every(r => { const b = of(n, r).body; return (n === 'alice' || !b.includes(idA)) && (n === 'bob' || !b.includes(idB)); })), 'an id leaked into another visitor\'s page');check('Bob\'s name is in his page and in nobody else\'s', of('bob', 1).body.includes('Bobby') && !of('alice', 1).body.includes('Bobby') && !of('out', 1).body.includes('Bobby'), 'Bobby not where expected');check('the three visitors get three different pages', new Set(['alice', 'bob', 'out'].map(n => of(n, 2).body)).size === 3, 'two visitors got the same page');check('each visitor gets, from the kept page, the same bytes as the first time', ['alice', 'bob', 'out'].every(n => of(n, 1).body === of(n, 0).body && of(n, 2).body === of(n, 0).body), 'a kept page differs from the first one');check('and every one of those was served without building the page', seq.filter(x => x.round > 0).every(x => x.reads === 1), J(seq.map(x => x.reads)));} catch (e) {check('the readme cache gate ran to its end', false, String(e && e.stack || e));} finally {for (const p of procs) { try { p.kill('SIGTERM'); } catch {} }if (ident) await ident.stop();await sleep(500);console.log(`\n${passes} passed, ${failures} failed`);process.exit(failures ? 1 : 0);}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- 727cd083gitoria#25: README: vendor notes for Hybriel c1b1010f and the page cachemre
- 61b72dedgitoria#25: re-vendor Hybriel master c1b1010f (W149 page cache), key the repo Readme page by slug and main commit, extend the readme-cache gatemre
- 5b0b4b9ereadme-cache gate: use the security gate's ports when no own ports are givenmre
- bc8f20d9gitoria#25: re-vendor Hybriel c09538bb with the W141 render cache, cache the homepage per commit, add the readme-cache gatemre
- 9feebbd3Re-vendor Hybriel to ded47c13 (W145: Firefox start script fix)mre
- 28ed41e5gitoria#24: one sign-in comes from hl:web batch 20, the /session/share workaround is gonemre
- 3b2669e4gs: drop the unbuildable legacy check, fix pwa fetchmre
- 2a2fdd77gs: C2 check before cookie experimentsmre
- 76e0587aWIP gs 2mre
- a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
- 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
- a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
- a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
- 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
- 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
- ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
- b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
- 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
- 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
- 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre