gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commite307d69ae307d69agitoria: say what is per process during the hand-overmree307d69a/tests/readme-cache.mjs

10.9 KB

  1. // tests/readme-cache.mjs — THE README CACHE GATE (gitoria#25): a repeat request for a repo's README must not read git again
  2. // (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
  3. // every call the server makes, so the gate counts git calls: a request that is served from the cache runs for-each-ref only
  4. // (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
  5. // for byte the one that was built. Real HTTP against a real local gitoria + its own ident (tests/identkit.mjs), the REAL git
  6. // binary for the pushes (into the bare repository on disk).
  7. // 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)
  8. import { spawn, execFileSync } from 'node:child_process';
  9. import { request } from 'node:http';
  10. import { mkdirSync, rmSync, writeFileSync, readFileSync, existsSync, chmodSync } from 'node:fs';
  11. import { dirname, join, resolve } from 'node:path';
  12. import { fileURLToPath } from 'node:url';
  13. import { startIdent } from './identkit.mjs';
  14. const HERE = dirname(fileURLToPath(import.meta.url));
  15. const APP = resolve(HERE, '..');
  16. 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);
  17. 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')));
  18. const STORE = join(APP, '.scratch/rc-store');
  19. const J = JSON.stringify, sleep = (ms) => new Promise(r => setTimeout(r, ms));
  20. let passes = 0, failures = 0;
  21. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  22. function raw(port, method, path, { host = `localhost:${port}`, headers = {}, body = null, cookie = null } = {}) {
  23. return new Promise((res, rej) => {
  24. const h = { host, ...headers }; if (cookie) h.cookie = cookie;
  25. if (body !== null) h['content-length'] = Buffer.byteLength(body);
  26. 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') })); });
  27. r.on('error', rej); if (body !== null) r.write(body); r.end();
  28. });
  29. }
  30. const get = (path, o = {}) => raw(PORT, 'GET', path, o);
  31. const sleepUp = async (srv) => {
  32. for (let i = 0; i < 960; i++) { try { if ((await raw(PORT, 'GET', '/api/repos')).status === 200) return; } catch {} await sleep(250); }
  33. throw new Error('gitoria did not come up\n' + srv.log());
  34. };
  35. const procs = [];
  36. let ident;
  37. try {
  38. rmSync(STORE, { recursive: true, force: true }); mkdirSync(join(STORE, 'shim'), { recursive: true });
  39. const LOG = join(STORE, 'git-calls.log');
  40. writeFileSync(join(STORE, 'shim/git'), `#!/bin/sh\necho "$@" >> "${LOG}"\nexec /usr/bin/git "$@"\n`); chmodSync(join(STORE, 'shim/git'), 0o755);
  41. writeFileSync(LOG, '');
  42. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  43. const alice = await ident.signIn('[email protected]');
  44. const BASE = `http://localhost:${PORT}`;
  45. const app = await ident.registerApp(alice, 'gitoria (readme cache gate)', [BASE]);
  46. let slog = '';
  47. const p = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  48. 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',
  49. GITORIA_STORAGE: join(STORE, 'mpackdb'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_GIT: join(STORE, 'git'),
  50. IDENT_URL: ident.base, IDENT_EXCHANGE_URL: ident.base, IDENT_API_KEY: app.key, IDENT_API_SECRET: app.secret } });
  51. p.stdout.on('data', d => slog += d); p.stderr.on('data', d => slog += d); procs.push(p);
  52. await sleepUp({ log: () => slog });
  53. const cookieOf = (r) => (r.headers['set-cookie'] || []).map(c => c.split(';')[0])[0] || null;
  54. const ck0 = cookieOf(await get('/'));
  55. const code = await ident.selectorCode(alice, app, BASE);
  56. const cb = await get('/login/callback?ident_code=' + code + '&next=%2F', { cookie: ck0 });
  57. const A = { cookie: cookieOf(cb) || ck0 };
  58. let n = 0;
  59. const face = async (who, event, payload) => {
  60. 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 }) });
  61. let j = null; try { j = JSON.parse(r.body); } catch {}
  62. return { status: r.status, value: j && j.value, error: j && j.error };
  63. };
  64. await face(A, 'gitoriaSaveName', ['Alice']);
  65. const mk = await face(A, 'gitoriaCreate', ['alpha', 'cache gate repo']);
  66. check('the gate repo is created', !!(mk.value && mk.value.repo && mk.value.repo.slug === 'alpha'), J(mk.value));
  67. // push a README into the bare repository on disk with the real git binary
  68. const bare = join(STORE, 'git', 'alpha.git'), work = join(STORE, 'work');
  69. const g = (cwd, ...a) => execFileSync('/usr/bin/git', ['-c', 'user.name=Gate', '-c', '[email protected]', ...a], { cwd, stdio: 'pipe' }).toString();
  70. mkdirSync(work, { recursive: true }); g(work, 'init', '-q', '-b', 'main');
  71. 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'); };
  72. const calls = () => { const t = readFileSync(LOG, 'utf8'); writeFileSync(LOG, ''); return t.split('\n').filter(Boolean); };
  73. const has = (cs, sub) => cs.some(c => c.includes(' ' + sub));
  74. // The page key (lib/pagekey.hl) reads the branches with one for-each-ref. Building the page runs homepageNow, which reads them
  75. // once more. So one for-each-ref in a request means the finished page was served without building it (gitoria#25, W149).
  76. const refReads = (cs) => cs.filter(c => c.includes(' for-each-ref')).length;
  77. const page = () => get('/', { host: `alpha.localhost:${PORT}` });
  78. const body = (r) => r.body.replace(/"at":\d+/g, '"at":T');
  79. push('# First title\n\nthe first README text FIRSTMARK\n');
  80. calls();
  81. const r1 = await page(); const c1 = calls();
  82. check('first README request shows the README', r1.status === 200 && r1.body.includes('FIRSTMARK'), `status ${r1.status}`);
  83. check('first request reads git for the tree and the file (built)', has(c1, 'ls-tree') && has(c1, 'cat-file'), J(c1));
  84. const r2 = await page(); const c2 = calls();
  85. check('a repeat request shows the same README', r2.status === 200 && r2.body.includes('FIRSTMARK'));
  86. 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));
  87. check('the cached HTML is byte for byte the built HTML', body(r1) === body(r2), `${r1.body.length} vs ${r2.body.length} bytes`);
  88. const r3 = await page(); const c3 = calls();
  89. check('a third request is still served from the cache', !has(c3, 'ls-tree') && !has(c3, 'cat-file') && body(r3) === body(r1), J(c3));
  90. push('# Second title\n\nthe second README text SECONDMARK\n');
  91. calls();
  92. const r4 = await page(); const c4 = calls();
  93. 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');
  94. check('after a push the homepage is built again', has(c4, 'ls-tree') && has(c4, 'cat-file'), J(c4));
  95. const r5 = await page(); const c5 = calls();
  96. check('and the new README is cached in turn', r5.body.includes('SECONDMARK') && !has(c5, 'ls-tree') && body(r5) === body(r4), J(c5));
  97. // W149 / gitoria#25: the finished page is served again without building it
  98. check('the first request built the page: the branches were read twice (key + homepage)', refReads(c1) === 2, J(c1));
  99. 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]));
  100. check('after a push the page is built again, then served kept', refReads(c4) === 2 && refReads(c5) === 1, J([c4, c5]));
  101. // three visitors: signed in as Alice, signed in as Bob, signed out. Each gets the shell of their own session.
  102. const bobU = await ident.signIn('[email protected]');
  103. const bcode = await ident.selectorCode(bobU, app, BASE);
  104. const bck0 = cookieOf(await get('/'));
  105. const bcb = await get('/login/callback?ident_code=' + bcode + '&next=%2F', { cookie: bck0 });
  106. const B = { cookie: cookieOf(bcb) || bck0 };
  107. await face(B, 'gitoriaSaveName', ['Bobby']);
  108. const visit = (who) => get('/', { host: `alpha.localhost:${PORT}`, cookie: who && who.cookie });
  109. const seq = [];
  110. 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()) }); }
  111. const of = (name, round) => seq.find(x => x.name === name && x.round === round);
  112. // the shell carries the visitor: the signed-in user's id is in the page, and the page of anyone else does not have it
  113. const idIn = (b) => (/"session":\{"user":\{"id":"([^"]+)"/.exec(b) || [])[1] || null;
  114. const idA = idIn(of('alice', 0).body), idB = idIn(of('bob', 0).body);
  115. 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)]));
  116. 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');
  117. 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');
  118. 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');
  119. 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');
  120. 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)));
  121. } catch (e) {
  122. check('the readme cache gate ran to its end', false, String(e && e.stack || e));
  123. } finally {
  124. for (const p of procs) { try { p.kill('SIGTERM'); } catch {} }
  125. if (ident) await ident.stop();
  126. await sleep(500);
  127. console.log(`\n${passes} passed, ${failures} failed`);
  128. process.exit(failures ? 1 : 0);
  129. }

Branches

Latest commits

  • e307d69agitoria: say what is per process during the hand-overmre
  • f0cbe6a6gitoria: standby service on port 45014 and a deploy that hands over through it without a gapmre
  • 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