gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchw7eeaea980report 007: say which runs included the removed checkmrew7/tests/realdata-offline.mjs

9.4 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. // real keys at the end of the text (the plain textarea offline: <md-editor> is not there — Hybriel gap, report 007)
  86. const md = await p.evaluate(`!!customElements.get('md-editor')`);
  87. if (md) {
  88. 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 }; })()`);
  89. 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 });
  90. } else { await p.click('#notetext'); }
  91. await p.send('Input.dispatchKeyEvent', { type: 'rawKeyDown', modifiers: 2, key: 'End', code: 'End', windowsVirtualKeyCode: 35, nativeVirtualKeyCode: 35 });
  92. await p.send('Input.dispatchKeyEvent', { type: 'keyUp', modifiers: 2, key: 'End', code: 'End', windowsVirtualKeyCode: 35, nativeVirtualKeyCode: 35 });
  93. const add = ' (offline edit, mission 007)';
  94. 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 }); }
  95. await sleep(2500);
  96. console.log('look 1280 offline:', await look()); await shot('1280-offline');
  97. await size(390, 844); console.log('look 390 offline:', await look()); await shot('390-offline'); await size(1280, 900);
  98. const typed = await p.evaluate(`document.getElementById('notetext').value`);
  99. 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)));
  100. await offline(false);
  101. let after = null;
  102. for (let i = 0; i < 120; i++) { after = (await api('/api/notes?id=' + target)).text; if (after === before + add) break; await sleep(250); }
  103. const live2 = await alive();
  104. 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 }));
  105. check('the server logged no error', !/error|Error/.test(log.replace(/error absorbed/g, '')), log.slice(-400));
  106. } catch (e) {
  107. console.log('FAIL crashed — ' + (e && e.stack || e)); failures++; console.log(log.slice(-1000));
  108. } finally {
  109. if (b) { try { await b.close(); } catch {} }
  110. try { srv.kill('SIGTERM'); } catch {}
  111. await sleep(1000);
  112. rmSync(W, { recursive: true, force: true });
  113. console.log(`${passes} passed, ${failures} failed (copy deleted: ${!existsSync(W)})`);
  114. process.exit(failures ? 1 : 0);
  115. }

Branches

Latest commits

  • 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
  • 9acc27f8notes mission 003 (#5): GitHub pipe tables in md-editor (parse, render, type, write) + gate checksmre
  • 2149e902notes mission 002 (4/4): code order — README file map + same-output test, STATUS, LOG, report; tests/letcount.py, tests/realdata-baseline.mjs, tests/realdata-compare.pymre
  • 47db4fc1notes mission 002 (3/4): code order — let only where reassigned (58 dropped; 34 left: 19 reassigned, 15 loop-bound); gates 50/0 + 18/0, live-data run = step 2mre