gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf3dec0f1f3dec0f1Merge branch 'w7'mref3dec0f1/tests/realdata-offline.mjs

12.3 KB

  1. // tests/realdata-offline.mjs (notes#4, mission 007): the offline notes on a COPY of real data, in real Chrome.
  2. // node tests/realdata-offline.mjs <backup.tgz> <port> <chrome-from>-<chrome-to>
  3. // Unpacks storage/mpackdb of the backup into .scratch/realdata-offline (a fresh copy, deleted at the end), signs in as the
  4. // creator (identity az5b2 → users @id 0muh6o5a3kkd) through a session file written before the start, then: every live
  5. // note is listed; screenshots 390 / 1280; Chrome offline (CDP, page + worker), reload offline, edit a note with real keys;
  6. // back online → the server has the edit (in that note, no copy). Kills only what it started.
  7. import { spawn, execFileSync } from 'node:child_process';
  8. import { writeFileSync, mkdirSync, rmSync, existsSync } from 'node:fs';
  9. import { createHash, randomBytes } from 'node:crypto';
  10. import { join, resolve, dirname } from 'node:path';
  11. import { fileURLToPath } from 'node:url';
  12. import { launchBrowser } from './cdp.mjs';
  13. const [tgz, portArg, chromeArg] = process.argv.slice(2);
  14. const APP = resolve(dirname(fileURLToPath(import.meta.url)), '..');
  15. const PORT = Number(portArg);
  16. const [CH_FROM, CH_TO] = (chromeArg || '8735-8739').split('-').map(Number);
  17. const BASE = `http://notes.test:${PORT}`, API = `http://127.0.0.1:${PORT}`;
  18. const W = join(APP, '.scratch/realdata-offline');
  19. const USER = '0muh6o5a3kkd';
  20. if (!process.env.HL_CHROME && existsSync('/opt/google/chrome/chrome')) process.env.HL_CHROME = '/opt/google/chrome/chrome';
  21. process.env.HL_CHROME_ARGS = `--host-resolver-rules=MAP notes.test 127.0.0.1|--unsafely-treat-insecure-origin-as-secure=${BASE}`;
  22. rmSync(W, { recursive: true, force: true });
  23. mkdirSync(join(W, 'data'), { recursive: true }); mkdirSync(join(W, 'sessions'), { recursive: true });
  24. execFileSync('tar', ['-xzf', resolve(tgz), '-C', join(W, 'data'), 'storage/mpackdb']);
  25. const sid = randomBytes(16).toString('hex');
  26. const now = Date.now();
  27. writeFileSync(join(W, 'sessions', createHash('sha256').update(sid).digest('hex')),
  28. JSON.stringify({ created: now, data: { tag: 'rd-offline' }, handled: [], id: sid, seen: now, user: { id: USER } }), { mode: 0o600 });
  29. const COOKIE = 'notessid=' + sid;
  30. let failures = 0, passes = 0;
  31. const check = (label, ok, detail = '') => { console.log(`${ok ? 'ok ' : 'FAIL'} ${label}${ok ? '' : ' — ' + detail}`); if (ok) passes++; else failures++; };
  32. const sleep = (ms) => new Promise(r => setTimeout(r, ms));
  33. const J = JSON.stringify;
  34. let log = '';
  35. const srv = spawn(join(APP, 'bin/hybriel'), ['project.hl'], { cwd: APP, stdio: ['ignore', 'pipe', 'pipe'],
  36. env: { ...process.env, NOTES_PORT: String(PORT), NOTES_PUBLIC_URL: BASE, NOTES_STORAGE: join(W, 'data/storage/mpackdb'),
  37. NOTES_SESSIONS: join(W, 'sessions') + '/', NOTES_WATCH: '0', IDENT_URL: 'http://ident.test', IDENT_API_KEY: 'pk_rd', IDENT_API_SECRET: 'sk_rd' } });
  38. srv.stdout.on('data', d => log += d); srv.stderr.on('data', d => log += d);
  39. let b = null;
  40. const api = async (path) => (await fetch(API + path, { headers: { cookie: COOKIE } })).json();
  41. const alive = async () => (await api('/api/notes')).notes.filter(n => !n.gone);
  42. try {
  43. for (let i = 0; i < 480; i++) { try { if ((await fetch(API + '/')).ok) break; } catch {} await sleep(250); }
  44. check('the session is the creator', (await api('/api/me')).user === USER);
  45. const live = await alive();
  46. console.log('live notes in the copy:', live.length);
  47. b = await launchBrowser({ debugPortRange: [CH_FROM, CH_TO] });
  48. const p = await b.newPage();
  49. p.__browser = b;
  50. await p.send('Network.enable');
  51. await p.send('Network.setCookie', { name: 'notessid', value: sid, url: BASE + '/' });
  52. const size = async (w, h) => { await p.send('Emulation.setDeviceMetricsOverride', { width: w, height: h, deviceScaleFactor: 1, mobile: w < 600 }); await sleep(300); };
  53. const shot = async (name) => { const { data } = await p.send('Page.captureScreenshot', { format: 'png' }); writeFileSync(join(APP, '.scratch', `realdata-${name}.png`), Buffer.from(data, 'base64')); };
  54. const look = () => p.evaluate(`JSON.stringify((() => { const c = (s) => { const e = document.querySelector(s); if (!e) return null; const st = getComputedStyle(e); const r = e.getBoundingClientRect(); return { color: st.color, bg: st.backgroundColor, w: Math.round(r.width), h: Math.round(r.height), vis: r.width > 0 && st.display !== 'none' }; };
  55. return { list: c('note-list'), reader: c('note-reader'), header: c('application-header'), brand: c('application-header .brand'), selected: c('#notes a.selected'), item: c('#notes a'), md: c('md-editor'), ta: c('#notetext'), state: (document.getElementById('syncstate') || {}).textContent, overflow: document.documentElement.scrollWidth > innerWidth, mdDefined: !!customElements.get('md-editor') }; })())`);
  56. await size(1280, 900);
  57. await p.goto(BASE + '/');
  58. await p.waitFor('document.querySelectorAll("#notes a").length > 0', { timeout: 60000 });
  59. await sleep(1000);
  60. const shown = await p.evaluate(`[...document.querySelectorAll('#notes a')].map(a => a.getAttribute('href').slice(6))`);
  61. check(`all ${live.length} live notes are listed (by id)`, shown.length === live.length && live.every(n => shown.includes(n.id)), `${shown.length} shown`);
  62. await p.waitFor('!!navigator.serviceWorker.controller', { timeout: 30000 });
  63. // the note to edit: the newest one; open it
  64. const target = shown[0];
  65. const before = (await api('/api/notes?id=' + target)).text;
  66. await p.click('#notes a');
  67. await p.waitFor(`location.pathname === '/note/${target}' && document.getElementById('notetext') && document.getElementById('notetext').value === ${J(before)}`, { timeout: 30000 });
  68. await sleep(1500);
  69. console.log('look 1280 online:', await look()); await shot('1280-online');
  70. await size(390, 844); console.log('look 390 online:', await look()); await shot('390-online');
  71. await size(1280, 900);
  72. // Chrome offline: page + worker, then reload offline
  73. const conn = b.conn; const workers = [];
  74. for (const t of (await conn.send('Target.getTargets')).targetInfos.filter(t => t.type === 'service_worker')) {
  75. const { sessionId } = await conn.send('Target.attachToTarget', { targetId: t.targetId, flatten: true });
  76. await conn.send('Network.enable', {}, sessionId); workers.push(sessionId);
  77. }
  78. const offline = async (o) => { await p.setOffline(o); for (const s of workers) await conn.send('Network.emulateNetworkConditions', { offline: o, latency: 0, downloadThroughput: -1, uploadThroughput: -1 }, s); };
  79. await offline(true);
  80. await p.goto(BASE + '/note/' + target);
  81. await p.waitFor(`!!window.__hl && document.getElementById('notetext') && document.getElementById('notetext').value === ${J(before)}`, { timeout: 30000 });
  82. await sleep(1500);
  83. const offCount = await p.evaluate(`document.querySelectorAll('#notes a').length`);
  84. check(`offline reload: all ${live.length} notes still listed, the open note shows its text, no socket`, offCount === live.length && !(await p.evaluate('!!(window.__hl.socket && window.__hl.socket.readyState === 1)')), String(offCount));
  85. // MOBILE (mission 008): the offline pages at 390 px measured in the DOM: no visible element wider than 390 (shadow DOM
  86. // included), every visible tap target (a, button, input, textarea, select, [role=button]) at least 44 x 44 px
  87. const measure = (label) => p.evaluate(`JSON.stringify((() => { const wide = [], small = [], seen = [];
  88. const walk = (root) => { for (const e of root.querySelectorAll('*')) { if (e.shadowRoot) walk(e.shadowRoot);
  89. const r = e.getBoundingClientRect(); const st = getComputedStyle(e); if (!r.width || !r.height || st.display === 'none' || st.visibility === 'hidden') continue;
  90. if (e.matches('md-editor > textarea') && customElements.get('md-editor')) continue; /* the editor keeps its textarea out of sight */
  91. const name = e.tagName.toLowerCase() + (e.id ? '#' + e.id : '') + (e.className && typeof e.className === 'string' ? '.' + e.className.trim().split(/\\s+/).join('.') : '');
  92. if (r.right > 390.5 || r.left < -0.5) wide.push(name + ' ' + Math.round(r.left) + '..' + Math.round(r.right));
  93. if (e.matches('a, button, input:not([type=hidden]), textarea, select, [role=button], [contenteditable]') && (r.height < 43.5 || r.width < 43.5)) small.push(name + ' ' + Math.round(r.width) + 'x' + Math.round(r.height) + ' "' + (e.textContent || '').trim().slice(0, 20) + '"');
  94. if (e.matches('a, button, input:not([type=hidden]), textarea, select, [role=button], [contenteditable]')) seen.push(name); } };
  95. walk(document); return { scrollW: document.documentElement.scrollWidth, innerW: innerWidth, wide: wide.slice(0, 8), small: small.slice(0, 12), taps: seen.length, editor: !!customElements.get('md-editor') }; })())`).then(JSON.parse);
  96. await size(390, 844);
  97. for (const [what, url, ready] of [['note', BASE + '/note/' + target, `!!document.getElementById('notetext')`], ['list', BASE + '/', `document.querySelectorAll('#notes a').length > 0`]]) {
  98. await p.goto(url);
  99. try { await p.waitFor(`!!window.__hl && ${ready}`, { timeout: 30000 }); } catch (e) { console.log('DEBUG', what, await p.evaluate(`JSON.stringify({ path: location.pathname, hl: !!window.__hl, nt: !!document.getElementById('notetext'), body: document.body.innerText.slice(0, 300) })`)); throw e; }
  100. await sleep(2000);
  101. const m = await measure(what);
  102. console.log('390 offline ' + what + ':', J(m));
  103. check(`390 px offline, ${what}: the editor script ran (md-editor defined)`, what === 'list' || m.editor, J(m));
  104. check(`390 px offline, ${what}: no element wider than 390 px, page scroll width ${m.scrollW}`, m.scrollW <= 390 && m.wide.length === 0, J(m.wide));
  105. check(`390 px offline, ${what}: ${m.taps} tap targets, all at least 44 x 44 px`, m.small.length === 0 && m.taps > 0, J(m.small));
  106. }
  107. await size(1280, 900);
  108. await p.goto(BASE + '/note/' + target);
  109. await p.waitFor(`!!window.__hl && document.getElementById('notetext') && document.getElementById('notetext').value === ${J(before)}`, { timeout: 30000 });
  110. await sleep(1500);
  111. // real keys at the end of the text (<md-editor> offline since hybriel#170)
  112. const md = await p.evaluate(`!!customElements.get('md-editor')`);
  113. if (md) {
  114. const bx = await p.evaluate(`(() => { const r = document.getElementById('notetext').closest('md-editor').shadowRoot.querySelector('[part~=editor]').getBoundingClientRect(); return { x: r.left + 20, y: r.top + 10 }; })()`);
  115. for (const [type, buttons] of [['mouseMoved', 0], ['mousePressed', 1], ['mouseReleased', 0]]) await p.send('Input.dispatchMouseEvent', { type, x: bx.x, y: bx.y, button: 'left', clickCount: 1, buttons });
  116. } else { await p.click('#notetext'); }
  117. await p.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'End', code: 'End', windowsVirtualKeyCode: 35, nativeVirtualKeyCode: 35 });
  118. await p.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'End', code: 'End', windowsVirtualKeyCode: 35, nativeVirtualKeyCode: 35 });
  119. const add = ' (offline edit, mission 007)';
  120. for (const ch of add) { await p.send('Input.dispatchKeyEvent', { type: 'keyDown', text: ch, unmodifiedText: ch, key: ch }); await p.send('Input.dispatchKeyEvent', { type: 'keyUp', key: ch }); }
  121. await sleep(2500);
  122. console.log('look 1280 offline:', await look()); await shot('1280-offline');
  123. await size(390, 844); console.log('look 390 offline:', await look()); await shot('390-offline'); await size(1280, 900);
  124. const typed = await p.evaluate(`document.getElementById('notetext').value`);
  125. check('offline: the edit is in the note, the server does not have it yet', typed === before + add && (await api('/api/notes?id=' + target)).text === before, J(typed.slice(-60)));
  126. await offline(false);
  127. let after = null;
  128. for (let i = 0; i < 120; i++) { after = (await api('/api/notes?id=' + target)).text; if (after === before + add) break; await sleep(250); }
  129. const live2 = await alive();
  130. check('back online: the offline edit synced into the same note (no copy, same count)', after === before + add && live2.length === live.length, J({ tail: (after || '').slice(-60), n: live2.length }));
  131. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  132. } catch (e) {
  133. console.log('FAIL crashed — ' + (e && e.stack || e)); failures++; console.log(log.slice(-1000));
  134. } finally {
  135. if (b) { try { await b.close(); } catch {} }
  136. try { srv.kill('SIGTERM'); } catch {}
  137. await sleep(1000);
  138. rmSync(W, { recursive: true, force: true });
  139. console.log(`${passes} passed, ${failures} failed (copy deleted: ${!existsSync(W)})`);
  140. process.exit(failures ? 1 : 0);
  141. }

Branches

Latest commits

  • f3dec0f1Merge branch 'w7'mre
  • d1cf966dre-vendor hybriel 97bcf128: offlineFiles for the editor script, 44 px taps, 390 px offline checks, mission 008mre
  • 4a610a21paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • eeaea980report 007: say which runs included the removed checkmre
  • 8a8ad9banotes mission 007: report, LOG, STATUSmre
  • 2cce9c96code order: plain declarations where never reassigned (letcount 0 never); gate: scan every IndexedDB at log-out, soft mode for old-code runs, drop a check that could not failmre
  • 7f6a4090README: offline in Hybriel (hl:web offline, continuation, known md-editor gap); gate waits report instead of crash; realdata-offline checkmre
  • 632223f2notes#4: delete notes-offline.js and sw.js (hl:web's generated worker and kept state replace them)mre
  • 52a2acadgate: offline checks on hl:web's worker/queue, Chrome offline via CDP (reload offline first), one-offline conflict, log-out forgets the kept copymre
  • e5785b03notes#4: the notes page in Hybriel — hl:web offline = [Notes], queued faces notesPut/notesDrop, push notesChanged, value-form notesPull on a tick; notes-offline.js/sw.js no longer loaded or routedmre
  • 510aff75notes#4: server continues a run of saves of one login (by + since), loser keeps writing into its copy; notesFor listmre
  • 0176c4b5mission brief 007mre
  • 06cfa870notes mission 006: re-vendor hybriel 0f396652 (static), reportmre
  • 6c07bd91mission brief w6mre
  • cf64d3d5notes mission 005: stopped at a Hybriel gap (for list repainted during hl:web boot throws, rowKidless); report, LOG, STATUSmre
  • a43b5d2dmission brief 005mre
  • 04a625edmission 004: re-vendor hybriel a832f73b (native bin + plugins as tickets), compose HL_CACHE_DIR volume + tmpfs /tmp, deploy URL wait 120 s, tests wait 120 s per start; gate 57/0 old and new; real-data same output. Not deployed.mre
  • aefb9d44mission brief w4mre
  • 202098b3docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 304f6a9dnotes mission 003 (#5): report, STATUS, LOGmre