gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmainfe209ffeMerge branch 'w56-owner-members' into mainGitoriamain/tests/chain.mjs

15.0 KB

  1. import { requiredPort, requiredPortRange } from './gate-ports.mjs';
  2. // tests/chain.mjs — gitoria#22: WHAT A TAB CLICK REPLACES, MEASURED IN A REAL CHROME WITH REAL CLICKS (C2's method).
  3. // Own ident + gitoria on a copy of the data (localhost hosts: alpha.localhost resolves to 127.0.0.1 in Chrome itself). Seeds repos
  4. // `alpha` (README, code, a branch, a pull request), `longdoc` (a 2 003-line README) and `gamma` (empty) through the real UI.
  5. // Then, in the measuring browser, per viewport: Readme → Code → Pulls → Readme → Code on alpha with real clicks, a
  6. // MutationObserver counting the elements REMOVED / ADDED by each click, and the repo head, the tab nav and the page elements tagged with
  7. // a property BEFORE the click — after the click they must still be the SAME node objects (standing levels). Then the
  8. // README timing on `longdoc` (click Code → click Readme: click → README text in the DOM, long-task time, page-side).
  9. // Results: .scratch/chain-<label>.json + a table on stdout. Screenshots .scratch/chain-<label>-<viewport>-<step>.png.
  10. // CHAIN_SERVE=1 only seed + serve (prints READY, runs until SIGTERM) — start it OUTSIDE the lisbeth lock; CHAIN_MEASURE=1 only measure an
  11. // already serving app on CHAIN_PORT (the E2E part that goes under the lock).
  12. // CHAIN_APP=<app dir> the code under test (default: this app); CHAIN_LABEL=old|new; CHAIN_PORT=8720 CHAIN_IDENT_PORT=8721
  13. // CHAIN_CDP=http://127.0.0.1:9223 measure in lisbeth's Chrome (a reverse tunnel for CHAIN_PORT must exist; ONE tab is reused, nothing is
  14. // closed) — run it under `flock …/lisbeth.lock`. Without it a headless Chrome is launched.
  15. import { spawn, execFileSync } from 'node:child_process';
  16. import { rmSync, mkdirSync, writeFileSync, existsSync } from 'node:fs';
  17. import { dirname, join, resolve } from 'node:path';
  18. import { fileURLToPath } from 'node:url';
  19. import { launchBrowser, Page } from './cdp.mjs';
  20. import { startIdent } from './identkit.mjs';
  21. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  22. const HERE = dirname(fileURLToPath(import.meta.url));
  23. const OWN = resolve(HERE, '..');
  24. const APP = resolve(process.env.CHAIN_APP || OWN);
  25. const LABEL = process.env.CHAIN_LABEL || 'run';
  26. const PORT = requiredPort('CHAIN_PORT');
  27. const IDENT_PORT = requiredPort('CHAIN_IDENT_PORT');
  28. const CHROME_PORTS = requiredPortRange('CHAIN_CHROME');
  29. const BASE = `http://localhost:${PORT}`;
  30. const REPO = (s) => `http://${s}.localhost:${PORT}`;
  31. const IDENT_B = `http://localhost:${IDENT_PORT}`;
  32. const SCRATCH = join(OWN, '.scratch');
  33. const STORE = join(SCRATCH, 'chain-store-' + LABEL);
  34. const IDENT_DIR = process.env.GITORIA_GATE_IDENT_DIR || '/media/STORAGE/projects/WorldAPI/ident.worldapi.org';
  35. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  36. const J = JSON.stringify;
  37. mkdirSync(SCRATCH, { recursive: true });
  38. let server = null, ident = null, log = '';
  39. const out = { label: LABEL, app: APP, steps: [], timing: [] };
  40. function startServer(env) {
  41. server = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  42. env: { ...process.env, GITORIA_PORT: String(PORT), GITORIA_STORAGE: join(STORE, 'db'), GITORIA_SESSIONS: join(STORE, 'sessions') + '/', GITORIA_WATCH: '0', GITORIA_GIT: join(STORE, 'git'),
  43. GITORIA_PUBLIC_URL: BASE, IDENT_URL: IDENT_B, IDENT_EXCHANGE_URL: ident.base, ...env } });
  44. server.stdout.on('data', d => log += d); server.stderr.on('data', d => log += d);
  45. }
  46. async function serverUp() {
  47. for (let i = 0; i < 960; i++) { try { if ((await fetch(`http://127.0.0.1:${PORT}/api/repos`)).ok) return; } catch {} await sleep(250); }
  48. throw new Error('gitoria did not come up\n' + log);
  49. }
  50. const hydrated = (p) => p.waitFor('!!window.__hl && window.__hl.socket && window.__hl.socket.readyState === 1', { label: 'hydrated', timeout: 60000 });
  51. const shot = async (p, name) => { const { data } = await p.send('Page.captureScreenshot', { format: 'png' }); const f = join(SCRATCH, `chain-${LABEL}-${name}.png`); writeFileSync(f, Buffer.from(data, 'base64')); return f; };
  52. async function seed() {
  53. const b = await launchBrowser({ debugPortRange: CHROME_PORTS });
  54. const A = await b.newPage();
  55. try {
  56. await A.send('Emulation.setDeviceMetricsOverride', { width: 1280, height: 900, deviceScaleFactor: 1, mobile: false });
  57. await A.goto(IDENT_B + '/'); await A.waitForSelector('#email'); await hydrated(A);
  58. await A.type('#email', '[email protected]'); await A.click('#sendcode');
  59. await A.waitFor('/\\/code$/.test(location.pathname) && !!document.querySelector("#code")', { label: 'ident code page' }); await hydrated(A);
  60. await A.type('#code', ident.lastCode('[email protected]')); await A.click('#verify'); await A.waitForSelector('#signout, #menusignout', { timeout: 15000 });
  61. await A.goto(BASE + '/'); await A.waitForSelector('#loginbutton'); await hydrated(A);
  62. await A.click('#loginbutton'); await A.waitForSelector('#chooselist', { timeout: 15000 }); await hydrated(A); await A.click('#chooselist li:nth-child(1) :is(a, button)');
  63. await A.waitFor(`location.href === ${J(BASE + '/')} && !!document.querySelector("#nameform")`, { label: 'name prompt' }); await hydrated(A);
  64. await A.type('#displayname', 'alice'); await A.click('#namesave'); await A.waitFor('!document.querySelector("#nameform")'); await A.waitForSelector('#createform');
  65. for (const slug of ['alpha', 'longdoc', 'gamma']) {
  66. for (let attempt = 1; ; attempt++) { // a loaded machine drops a click now and then: look, then retry
  67. await A.evaluate('document.querySelector("#slug").value = ""; document.querySelector("#description").value = ""');
  68. await A.type('#slug', slug); await A.type('#description', 'repo ' + slug); await A.click('#createsave');
  69. try { await A.waitFor(`[...document.querySelectorAll('#repos .repo-slug')].some(a => a.textContent === ${J(slug)})`, { label: 'created ' + slug, timeout: 30000 }); break; }
  70. catch (e) { if (attempt >= 3) throw e; }
  71. }
  72. }
  73. } finally { await b.close(); }
  74. const push = (slug, files, extra = () => {}) => {
  75. const work = join(STORE, 'work-' + slug); rmSync(work, { recursive: true, force: true }); mkdirSync(work, { recursive: true });
  76. const git = (...a) => execFileSync('git', ['-C', work, '-c', 'user.name=t', '-c', '[email protected]', ...a], { stdio: 'pipe' });
  77. git('init', '-q', '-b', 'main');
  78. for (const [p, c] of Object.entries(files)) { mkdirSync(dirname(join(work, p)), { recursive: true }); writeFileSync(join(work, p), c); }
  79. git('add', '-A'); git('commit', '-q', '-m', 'files'); extra(git, work);
  80. git('push', '-q', '-f', join(STORE, 'git', slug + '.git'), '--all');
  81. };
  82. push('alpha', { 'README.md': '# Alpha\n\nSome **text** and a list:\n\n- one\n- two\n\n```\nlet x = 1\n```\n', 'src/a.txt': 'line one\nline two\n', 'b.txt': 'b\n' }, (git, work) => {
  83. writeFileSync(join(work, 'src', 'a.txt'), 'changed\n'); git('commit', '-qam', '|||PR add a change');
  84. });
  85. const lines = ['# A long README', ''];
  86. for (let i = 1; lines.length < 2003; i++) lines.push(`## Section ${i}`, '', `Paragraph ${i} with **strong**, *soft*, \`code\` and a [link](https://example.org/${i}) to show inline work.`, '', `- item ${i}.1`, `- item ${i}.2`, '');
  87. push('longdoc', { 'README.md': lines.join('\n') + '\n' });
  88. }
  89. // ---- measuring ---------------------------------------------------------------------------------------
  90. const OBSERVE = `(() => {
  91. window.__mo && window.__mo.disconnect();
  92. const c = (n) => n.nodeType === 1 ? 1 + n.getElementsByTagName('*').length : 0;
  93. window.__cnt = { removed: 0, added: 0 }; window.__lt = 0;
  94. window.__mo = new MutationObserver((recs) => { for (const r of recs) { for (const n of r.removedNodes) window.__cnt.removed += c(n); for (const n of r.addedNodes) window.__cnt.added += c(n); } });
  95. window.__mo.observe(document.body, { childList: true, subtree: true });
  96. try { window.__po && window.__po.disconnect(); window.__po = new PerformanceObserver((l) => { for (const e of l.getEntries()) window.__lt += e.duration; }); window.__po.observe({ entryTypes: ['longtask'] }); } catch {}
  97. return true; })()`;
  98. // tag the standing candidates; compare after the click (same object? still connected?)
  99. const TAG = `(() => { const q = (s) => document.querySelector(s); const m = { shell: q('main'), repoPage: q('main repo-page'), head: q('repo-head'), name: q('#reponame'), nav: q('#reponav'),
  100. navlinks: q('#reponav a'), header: q('application-header'), page: q('main repo-page > :last-child') };
  101. window.__tags = m; window.__ids = {}; for (const k in m) { if (m[k]) m[k].__tag = k + '#' + Math.random().toString(36).slice(2); window.__ids[k] = m[k] ? m[k].__tag : null; } return window.__ids; })()`;
  102. const CHECK = `(() => { const q = (s) => document.querySelector(s); const now = { shell: q('main'), repoPage: q('main repo-page'), head: q('repo-head'), name: q('#reponame'), nav: q('#reponav'),
  103. navlinks: q('#reponav a'), header: q('application-header'), page: q('main repo-page > :last-child') }; const r = {};
  104. for (const k in now) r[k] = !!now[k] && !!window.__ids[k] && now[k].__tag === window.__ids[k] && now[k].isConnected; return r; })()`;
  105. async function steps(P, vp, slug) {
  106. const rows = [];
  107. await P.goto(REPO(slug) + '/'); await P.waitFor('!!document.querySelector("#homepage")', { label: 'readme' }); await hydrated(P); await sleep(500);
  108. await P.evaluate(TAG);
  109. const seq = [['#navcode', '/code', '#entries', 'Readme→Code'], ['#navpulls', '/pulls', '#pullshelp', 'Code→Pulls'], ['#navhome', '/', '#homepage', 'Pulls→Readme'], ['#navcode', '/code', '#entries', 'Readme→Code (2nd)']];
  110. let n = 0;
  111. await P.evaluate(OBSERVE);
  112. rows.push({ shot: await shot(P, `${vp}-0-readme`) });
  113. for (const [link, path, sel, name] of seq) {
  114. await P.evaluate('window.__cnt.removed = 0; window.__cnt.added = 0; window.__lt = 0; 0');
  115. await P.click(link);
  116. await P.waitFor(`location.pathname === ${J(path)} && !!document.querySelector(${J(sel)})`, { label: name, timeout: 30000 });
  117. await sleep(700); // let the page settle: late additions are counted too
  118. const cnt = await P.evaluate('({ ...window.__cnt, longtask: Math.round(window.__lt) })');
  119. const kept = await P.evaluate(CHECK);
  120. const cur = await P.evaluate(`[...document.querySelectorAll('#reponav a[aria-current=page]')].map(a => a.id).join()`);
  121. rows.push({ step: name, ...cnt, kept, aria: cur, shot: await shot(P, `${vp}-${++n}-${path.replace(/\W/g, '') || 'readme'}`) });
  122. }
  123. return rows;
  124. }
  125. async function timing(P, vp) {
  126. const res = [];
  127. for (let i = 0; i < 3; i++) {
  128. await P.goto(REPO('longdoc') + '/code'); await P.waitFor('!!document.querySelector("#codemessage, #entries, #noentries")', { label: 'longdoc code', timeout: 60000 }); await hydrated(P); await sleep(800);
  129. await P.evaluate(OBSERVE);
  130. // page-side stopwatch: starts at the click's `pointerdown` (the real press), stops when the README text is in the DOM and painted (2 rAF)
  131. await P.evaluate(`(() => { window.__tm = { done: false }; const a = document.querySelector('#navhome');
  132. a.addEventListener('pointerdown', () => { window.__tm.t0 = performance.now(); const poll = () => { const m = document.querySelector('#homepage markdown-text'); if (m && m.querySelector('h2')) { requestAnimationFrame(() => requestAnimationFrame(() => { window.__tm.shown = performance.now() - window.__tm.t0; window.__tm.done = true; })); } else requestAnimationFrame(poll); }; poll(); }, { once: true }); return true; })()`);
  133. await P.click('#navhome');
  134. await P.waitFor('window.__tm.done', { timeout: 60000, label: 'readme shown' });
  135. await sleep(500);
  136. const t = await P.evaluate('({ shown: Math.round(window.__tm.shown), removed: window.__cnt.removed, added: window.__cnt.added, longtask: Math.round(window.__lt) })');
  137. res.push(t);
  138. }
  139. return { vp, runs: res };
  140. }
  141. const SERVE = process.env.CHAIN_SERVE === '1', MEASURE_ONLY = process.env.CHAIN_MEASURE === '1';
  142. try {
  143. if (!MEASURE_ONLY) {
  144. rmSync(STORE, { recursive: true, force: true }); mkdirSync(STORE, { recursive: true });
  145. ident = await startIdent({ identDir: IDENT_DIR, workDir: join(STORE, 'ident'), port: IDENT_PORT });
  146. const alice = await ident.signIn('[email protected]');
  147. const KEY = await ident.registerApp(alice, 'gitoria (chain)', [BASE]);
  148. startServer({ IDENT_API_KEY: KEY.key, IDENT_API_SECRET: KEY.secret });
  149. await serverUp();
  150. await seed();
  151. if (SERVE) {
  152. console.log('READY ' + BASE);
  153. await new Promise((r) => { process.on('SIGTERM', r); process.on('SIGINT', r); });
  154. throw new Error('stopped');
  155. }
  156. }
  157. // the measuring browser
  158. let P, B, own = true, keepUa = null;
  159. if (process.env.CHAIN_CDP) {
  160. process.env.HL_CDP_URL = process.env.CHAIN_CDP; B = await launchBrowser();
  161. const { targetInfos } = await B.conn.send('Target.getTargets');
  162. const t = targetInfos.find(x => x.type === 'page');
  163. const { sessionId } = await B.conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  164. P = new Page(B, t.targetId, sessionId); await P._init(); own = false;
  165. await P.send('Page.bringToFront'); // a background tab paints no frames: no screenshots, no requestAnimationFrame
  166. } else { B = await launchBrowser({ debugPortRange: CHROME_PORTS }); P = await B.newPage(); }
  167. for (const [vp, w, h, mobile] of [['desktop', 1280, 900, false], ['phone390', 390, 844, true]]) {
  168. await P.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: mobile ? 2 : 1, mobile });
  169. await sleep(300);
  170. const rows = await steps(P, vp, 'alpha');
  171. out.steps.push({ vp, rows });
  172. if (vp === 'phone390') {
  173. out.tapSizes = await P.evaluate(`[...document.querySelectorAll('#reponav a')].map(a => { const r = a.getBoundingClientRect(); return a.id + ':' + Math.round(r.width) + 'x' + Math.round(r.height); })`);
  174. out.noOverflow = await P.evaluate('document.documentElement.scrollWidth <= 390');
  175. }
  176. out.timing.push(await timing(P, vp));
  177. }
  178. await P.send('Emulation.clearDeviceMetricsOverride');
  179. writeFileSync(join(SCRATCH, `chain-${LABEL}.json`), J(out, null, 1));
  180. for (const s of out.steps) for (const r of s.rows) if (r.step) console.log(`${LABEL} ${s.vp.padEnd(9)} ${r.step.padEnd(22)} removed ${String(r.removed).padStart(4)} added ${String(r.added).padStart(4)} longtask ${r.longtask}ms aria-current=${r.aria} SAME NODE: ` + Object.entries(r.kept).map(([k, v]) => k + '=' + (v ? 'yes' : 'NO')).join(' '));
  181. for (const t of out.timing) console.log(`${LABEL} ${t.vp.padEnd(9)} longdoc Readme click→text painted (ms): ` + t.runs.map(r => `${r.shown} (removed ${r.removed}/added ${r.added}, longtask ${r.longtask})`).join(' | '));
  182. if (out.tapSizes) console.log(`${LABEL} phone tabs: ${out.tapSizes.join(' ')} no-overflow=${out.noOverflow}`);
  183. await B.close();
  184. } catch (e) { if (e.message !== 'stopped') { console.log('CHAIN FAILED ' + (e && e.stack || e)); process.exitCode = 1; } }
  185. finally {
  186. if (server) { try { server.kill('SIGTERM'); } catch {} }
  187. if (ident) await ident.stop();
  188. if (!MEASURE_ONLY) writeFileSync(join(SCRATCH, `chain-${LABEL}-server.log`), log);
  189. process.exit(process.exitCode || 0);
  190. }

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