Files
SHiNE-server/shine-UI/tests/stage1-2-initial-ping.test.mjs

283 lines
13 KiB
JavaScript

import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { runInNewContext } from 'node:vm';
const source = readFileSync(new URL('../js/app.js', import.meta.url), 'utf8');
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
const diagnostics = html.match(/<script id="shine-stage0-startup-diagnostics">([\s\S]*?)<\/script>/)?.[1];
assert.ok(diagnostics);
// Используются настоящие тела app.js; таймеры, WS, SW и DOM заменены детерминированными стендами.
const slices = [
['function finishInitialConnectionSplash()', 'function startConnectionCountdown()'],
['function setConnectionStatus(', 'async function triggerImmediateConnectionRetry()'],
['function extractBuildHashFromHtml(', 'function startPeriodicUiVersionCheck()'],
['async function checkConnectionHealth(', 'function isReconnectAllowedNow()'],
];
const chain = slices.map(([start, end]) => {
const a = source.indexOf(start);
const b = source.indexOf(end, a + start.length);
assert.ok(a >= 0 && b > a, `Невозможно извлечь ${start}`);
return source.slice(a, b);
}).join('\n');
function deferred() {
let resolve;
const promise = new Promise(r => { resolve = r; });
return { promise, resolve };
}
async function settle() {
await new Promise(resolve => setImmediate(resolve));
await new Promise(resolve => setImmediate(resolve));
}
function harness({ debug = true, ping = 'fast', sw = 'fast', wsOpen = true, localDemo = false } = {}) {
let currentMs = 400;
const performance = { now: () => ++currentMs, mark() {}, getEntriesByType: () => [] };
const window = { performance };
runInNewContext(diagnostics, { window, performance,
localStorage: { getItem: () => debug ? '1' : '0' }, document: { addEventListener() {} },
});
const log = [];
const intervals = new Map();
let nextInterval = 0;
let connected = wsOpen;
let fail = ping === 'fail';
const slowPing = ping === 'slow' ? deferred() : null;
const slowSw = sw === 'slow' ? deferred() : null;
window.setInterval = (callback, milliseconds) => {
const id = ++nextInterval;
log.push(['interval', milliseconds]);
intervals.set(id, { callback, milliseconds });
return id;
};
window.clearInterval = id => { log.push(['clear-interval']); intervals.delete(id); };
window.setTimeout = (_callback, milliseconds) => { log.push(['timeout', milliseconds]); return 123; };
window.location = { reload() { log.push(['reload']); } };
const splash = { classList: { add(name) { log.push(['splash', name]); } },
addEventListener() {}, remove() { log.push(['splash-remove']); } };
const navigator = sw === 'unavailable' ? {} : { serviceWorker: {
async getRegistrations() { log.push(['sw-registrations']); return [{
async update() {
log.push(['sw-update']);
if (slowSw) await slowSw.promise;
if (sw === 'fail') throw Object.assign(new Error('private token'), { name: 'SecurityError' });
},
}]; },
} };
const context = {
window, navigator, state: { session: { isLocalDemo: localDemo, isAuthorized: true } },
initialSplashEl: splash, initialConnectionCompleted: false,
connectionState: '', connectionStatusText: '', connectionNextRetryAtMs: 0,
connectionCheckInFlight: false, connectionMonitorStartSource: '', pingIntervalId: null,
CONNECTION_CHECK_INTERVAL_MS: 20000, pwaUpdateCheckAttempted: false,
uiVersionCheckInFlight: false, uiUpdateReloadScheduled: false,
wsIsOpen: () => connected,
authService: { ws: {
async open() { log.push(['ws-open']); connected = true; },
async request(op) {
log.push(['request', op]);
if (slowPing) await slowPing.promise;
if (fail) { fail = false; throw Object.assign(new Error('private token'), { name: 'NetworkError' }); }
return { uiBuildHash: 'same' };
},
} },
ensureSessionAfterWsReconnect: async () => { log.push(['ws-restore']); return true; },
stopConnectionCountdown: () => log.push(['countdown-stop']),
startConnectionCountdown: () => log.push(['countdown-start']),
refreshConnectionUi: () => log.push(['connection-ui']),
CURRENT_BUILD_HASH: 'same', UI_BUILD_HASH_PATTERN: /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/,
fetch: async () => { log.push(['fetch']); throw Error('Неожиданный fetch'); },
addAppLogEntry: () => log.push(['log']),
};
runInNewContext(chain, context);
const run = (fn) => runInNewContext(fn, context);
const count = (name) => log.filter(e => e[0] === name).length;
return { log, intervals, context, run, count,
start: (source) => run(`startConnectionMonitor('${source}')`),
health: (source) => run(`checkConnectionHealth('${source}')`),
tick: () => [...intervals.values()][0]?.callback(),
failNextPing: () => { fail = true; },
closeWs: () => { connected = false; },
releasePing: () => slowPing?.resolve(),
releaseSw: () => slowSw?.resolve(),
exportData: () => JSON.parse(window.__SHINE_STAGE0_EXPORT__()),
op: (name, source) => JSON.parse(window.__SHINE_STAGE0_EXPORT__()).splashTrace.operations
.filter(o => o.operation === name && (!source || o.context === source)),
};
}
// Реальный исходник обязан направлять события через те же фиксированные источники.
test('Идентификаторы соответствуют существующим call-site (bootstrap, session-runtime, reset, visibility и periodic)', () => {
assert.match(source, /startConnectionMonitor\('bootstrap'\)/);
assert.match(source, /startConnectionMonitor\('session_runtime'\)/);
assert.match(source, /startConnectionMonitor\('session_reset'\)/);
assert.match(source, /checkConnectionHealth\('visibility'\)/);
assert.match(source, /checkConnectionHealth\('periodic'\)/);
assert.match(source, /checkConnectionHealth\('retry_countdown'\)/);
assert.match(source, /checkConnectionHealth\('manual_retry'\)/);
assert.equal((source.match(/startConnectionMonitor\('bootstrap'\)/g) || []).length, 1);
assert.equal((source.match(/startConnectionMonitor\('session_runtime'\)/g) || []).length, 1);
});
test('Сохранённая сессия: bootstrap → session-runtime создаёт только один первоначальный Ping', async () => {
const h = harness({ sw: 'slow' });
h.start('bootstrap');
await settle();
h.start('session_runtime');
await settle();
assert.equal(h.count('request'), 1);
assert.equal(h.count('interval'), 1);
assert.equal(h.count('clear-interval'), 0);
assert.equal(h.intervals.size, 1);
assert.equal(h.count('sw-update'), 1);
assert.equal(h.context.connectionState, 'connected');
assert.equal(h.count('splash'), 1);
assert.equal(h.op('monitor_start', 'session_runtime')[0].outcome, 'deduplicated');
assert.equal(h.op('connection_health', 'bootstrap').length, 1);
assert.equal(h.op('connection_health', 'session_runtime').length, 0);
assert.equal(h.op('sw_registration_update')[0].outcome, 'pending');
h.releaseSw();
await settle();
assert.equal(h.op('sw_registration_update')[0].outcome, 'ok');
});
test('Сохранённая сессия: session-runtime → bootstrap также создаёт один Ping', async () => {
const h = harness();
h.start('session_runtime');
await settle();
h.start('bootstrap');
await settle();
assert.equal(h.count('request'), 1);
assert.equal(h.intervals.size, 1);
assert.equal(h.op('monitor_start', 'bootstrap')[0].outcome, 'deduplicated');
});
test('Без пользователя: bootstrap запускает Ping без блокирования monitor guard', async () => {
const h = harness();
h.context.state.session.isAuthorized = false;
h.start('bootstrap');
await settle();
assert.equal(h.count('request'), 1);
assert.equal(h.op('connection_health', 'bootstrap').length, 1);
assert.equal(h.intervals.size, 1);
});
test('Медленный Ping: параллельный старт не создаёт второй WS/Ping, Splash по ответу', async () => {
const h = harness({ ping: 'slow' });
h.start('bootstrap');
h.start('session_runtime');
assert.equal(h.count('request'), 1);
assert.equal(h.count('splash'), 0);
assert.equal(h.op('monitor_start', 'session_runtime')[0].outcome, 'deduplicated');
h.releasePing();
await settle();
assert.equal(h.count('request'), 1);
assert.equal(h.count('splash'), 1);
assert.equal(h.context.connectionState, 'connected');
});
test('Неудачный первый Ping: второй старт сохраняет самостоятельную немедленную повторную проверку', async () => {
const h = harness({ ping: 'fail' });
h.start('bootstrap');
await settle();
assert.equal(h.context.connectionState, 'disconnected');
h.start('session_runtime');
await settle();
assert.equal(h.count('request'), 2);
assert.equal(h.context.connectionState, 'connected');
assert.equal(h.op('monitor_start', 'session_runtime')[0].outcome, 'ok');
});
test('20-секундный Ping: исходный интервал и обычный повтор запроса сохранены', async () => {
const h = harness();
h.start('bootstrap');
await settle();
h.start('session_runtime');
assert.equal([...h.intervals.values()][0].milliseconds, 20000);
h.tick();
await settle();
assert.equal(h.count('request'), 2);
assert.equal(h.op('connection_health', 'periodic').length, 1);
assert.equal(h.count('interval'), 1);
assert.equal(h.count('sw-update'), 1);
});
test('Reconnect после успешного старта: visibility или другой реальный сигнал вызывает health-check и WS open', async () => {
const h = harness();
h.start('bootstrap');
await settle();
h.start('session_runtime');
h.closeWs();
await h.health('visibility');
assert.equal(h.count('request'), 2);
assert.equal(h.count('ws-open'), 1);
assert.equal(h.count('ws-restore'), 1);
assert.equal(h.count('sw-update'), 1);
assert.equal(h.op('connection_health', 'visibility').length, 1);
});
test('Возврат вкладки: независимая visibility-проверка не подавляется startup guard', async () => {
const h = harness();
h.start('session_runtime');
await settle();
h.start('bootstrap');
await h.health('visibility');
assert.equal(h.count('request'), 2);
assert.equal(h.op('monitor_start', 'bootstrap')[0].outcome, 'deduplicated');
assert.equal(h.op('connection_health', 'visibility')[0].outcome, 'ok');
});
test('Смена пользователя: session-reset и новый runtime сохраняют немедленные проверки', async () => {
const h = harness();
h.start('bootstrap');
await settle();
h.start('session_runtime');
h.start('session_reset');
await settle();
h.start('session_runtime');
await settle();
assert.equal(h.count('request'), 3);
assert.equal(h.op('monitor_start', 'session_reset')[0].outcome, 'ok');
assert.equal(h.op('monitor_start', 'session_runtime').at(-1).outcome, 'ok');
assert.equal(h.intervals.size, 1);
});
test('Stage 0/0.1/1.1: метки и безопасные context сохраняются, без чувствительных данных', async () => {
const h = harness({ sw: 'fail' });
h.start('bootstrap');
await settle();
h.start('session_runtime');
await settle();
const e = h.exportData();
assert.equal(e.counters.pingStarted, 1);
assert.equal(e.counters.pingCompleted, 1);
for (const name of ['connection_health','ping','pwa_first_ping_update','sw_refresh','sw_registration_update']) {
assert.ok(e.splashTrace.operations.some(x => x.operation === name), `Нет ${name}`);
}
assert.ok(e.timing.status_connected < e.timing.splash_leave || e.timing.status_connected === e.timing.splash_leave);
assert.ok(e.timing.splash_leave != null);
assert.equal(h.op('sw_registration_update')[0].errorType, 'SecurityError');
assert.ok(e.splashTrace.operations.some(x => x.operation === 'monitor_start' && x.outcome === 'deduplicated'));
assert.doesNotMatch(JSON.stringify(e), /private|token|sessionId|https?:/);
});
test('Debug-off: диагностика не нужна для корректного monitor guard и не создаёт запросов', async () => {
const h = harness({ debug: false, sw: 'unavailable' });
h.start('bootstrap');
await settle();
h.start('session_runtime');
assert.equal(h.count('request'), 1);
assert.equal(h.count('sw-update'), 0);
assert.equal(h.intervals.size, 1);
});
test('Local demo: никакого Ping при обеих startup-ветках', async () => {
const h = harness({ localDemo: true });
h.start('bootstrap');
h.start('session_runtime');
assert.equal(h.count('request'), 0);
assert.equal(h.intervals.size, 0);
assert.equal(h.context.connectionState, 'connected');
});