SHA256
295 lines
15 KiB
JavaScript
295 lines
15 KiB
JavaScript
import test from 'node:test';
|
||
import assert from 'node:assert/strict';
|
||
import { readFileSync } from 'node:fs';
|
||
import { runInNewContext } from 'node:vm';
|
||
|
||
const appSource = readFileSync(new URL('../js/app.js', import.meta.url), 'utf8');
|
||
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||
const diagnosticScript = html.match(/<script id="shine-stage0-startup-diagnostics">([\s\S]*?)<\/script>/)?.[1];
|
||
assert.ok(diagnosticScript);
|
||
|
||
// Реальные тела функций берутся из app.js; сетевые и DOM-операции заменены контролируемыми стендами.
|
||
const slices = [
|
||
['function finishInitialConnectionSplash()', 'function startConnectionCountdown()'],
|
||
['function setConnectionStatus(', 'async function triggerImmediateConnectionRetry()'],
|
||
['function extractBuildHashFromHtml(', 'function startPeriodicUiVersionCheck()'],
|
||
['async function checkConnectionHealth(', 'function startConnectionMonitor('],
|
||
];
|
||
function splashChain(source) {
|
||
return slices.map(([start, end]) => {
|
||
const from = source.indexOf(start);
|
||
const to = source.indexOf(end, from + start.length);
|
||
assert.ok(from >= 0 && to > from, `Не удалось извлечь ${start}`);
|
||
return source.slice(from, to);
|
||
}).join('\n');
|
||
}
|
||
function deferred() {
|
||
let resolve;
|
||
const promise = new Promise(r => { resolve = r; });
|
||
return { promise, resolve };
|
||
}
|
||
const settle = () => new Promise(resolve => setImmediate(resolve));
|
||
|
||
function harness({ source = appSource, slowSw = false, swError = false, swSupported = true,
|
||
initiallyConnected = true, remoteHash = 'same', hostHash = 'same' } = {}) {
|
||
let now = 10;
|
||
const performance = { now: () => ++now, mark() {}, getEntriesByType: () => [] };
|
||
const window = { performance };
|
||
runInNewContext(diagnosticScript, {
|
||
window, performance,
|
||
localStorage: { getItem: () => '1' }, document: { addEventListener() {} },
|
||
});
|
||
const log = [];
|
||
const pendingUpdate = slowSw ? deferred() : null;
|
||
let open = initiallyConnected;
|
||
let rejectNextPing = false;
|
||
const timers = [];
|
||
const splash = {
|
||
classList: { add(value) { log.push(['splash-class', value]); } },
|
||
addEventListener(event) { log.push(['splash-listener', event]); },
|
||
remove() { log.push(['splash-remove']); },
|
||
};
|
||
const registration = {
|
||
waiting: { postMessage(value) { log.push(['sw-message', value.type]); } },
|
||
async update() {
|
||
log.push(['sw-update']);
|
||
if (pendingUpdate) await pendingUpdate.promise;
|
||
if (swError) throw Object.assign(new Error('secret token'), { name: 'NetworkError' });
|
||
},
|
||
};
|
||
const navigator = swSupported ? {
|
||
serviceWorker: { async getRegistrations() { log.push(['sw-list']); return [registration]; } },
|
||
} : {};
|
||
window.setTimeout = (callback, milliseconds) => { log.push(['timer', milliseconds]); timers.push({ callback, milliseconds }); };
|
||
window.location = { reload() { log.push(['reload']); } };
|
||
const context = {
|
||
window, navigator, initialSplashEl: splash, initialConnectionCompleted: false,
|
||
connectionState: '', connectionStatusText: '', connectionNextRetryAtMs: 0,
|
||
CONNECTION_CHECK_INTERVAL_MS: 20000, connectionCheckInFlight: false,
|
||
pwaUpdateCheckAttempted: false, uiVersionCheckInFlight: false, uiUpdateReloadScheduled: false,
|
||
state: { session: { isLocalDemo: false } },
|
||
wsIsOpen: () => open,
|
||
authService: { ws: {
|
||
async open() { log.push(['ws-open']); open = true; },
|
||
async request(op) {
|
||
log.push(['request', op]);
|
||
if (rejectNextPing) {
|
||
rejectNextPing = false;
|
||
throw Object.assign(new Error('private network error'), { name: 'NetworkError' });
|
||
}
|
||
return { uiBuildHash: remoteHash };
|
||
},
|
||
} },
|
||
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(['ui-version-fetch']);
|
||
return { ok: true, async text() { return `window.__SHINE_BUILD_HASH__ = '${hostHash}'`; } };
|
||
},
|
||
addAppLogEntry: () => log.push(['app-log']),
|
||
};
|
||
runInNewContext(splashChain(source), context);
|
||
return {
|
||
log, timers, context, completeUpdate: () => pendingUpdate?.resolve(),
|
||
disconnect() { open = false; },
|
||
failNextPing() { rejectNextPing = true; },
|
||
async health() { await runInNewContext('checkConnectionHealth()', context); },
|
||
exportData() { return JSON.parse(window.__SHINE_STAGE0_EXPORT__()); },
|
||
};
|
||
}
|
||
const count = (h, name) => h.log.filter(event => event[0] === name).length;
|
||
const operation = (h, name, context = null) => h.exportData().splashTrace.operations.find(
|
||
event => event.operation === name && (!context || event.context === context),
|
||
);
|
||
|
||
// 1. Быстрый Ping, медленный SW: статус и Splash не ждут окончания update().
|
||
test('Быстрый Ping и медленный SW: connected и splash_leave раньше sw_registration_update:end', async () => {
|
||
const h = harness({ slowSw: true });
|
||
await h.health();
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
assert.equal(count(h, 'request'), 1);
|
||
assert.equal(count(h, 'sw-update'), 1);
|
||
assert.equal(count(h, 'splash-class'), 1);
|
||
assert.equal(operation(h, 'connection_health').outcome, 'ok');
|
||
assert.equal(operation(h, 'pwa_first_ping_update').outcome, 'pending');
|
||
assert.equal(operation(h, 'sw_registration_update').durationMs, null);
|
||
assert.ok(h.exportData().timing.status_connected <= h.exportData().timing.splash_leave);
|
||
h.completeUpdate();
|
||
await settle();
|
||
assert.equal(operation(h, 'sw_registration_update').outcome, 'ok');
|
||
assert.ok(operation(h, 'sw_registration_update').endMs > h.exportData().timing.splash_leave);
|
||
assert.equal(operation(h, 'pwa_first_ping_update').outcome, 'ok');
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
});
|
||
|
||
// 2. Зависший SW не удерживает connectionCheckInFlight и не блокирует Splash.
|
||
test('Зависший SW update: успешный health-check завершается без его разрешения', async () => {
|
||
const h = harness({ slowSw: true });
|
||
await h.health();
|
||
assert.equal(h.context.connectionCheckInFlight, false);
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
assert.equal(count(h, 'splash-class'), 1);
|
||
assert.equal(operation(h, 'sw_registration_update').outcome, 'pending');
|
||
assert.equal(operation(h, 'pwa_first_ping_update').durationMs, null);
|
||
assert.deepEqual(h.timers.map(t => t.milliseconds), [700]);
|
||
// Тестовый стенд разрешает Promise перед завершением, чтобы не оставлять незавершённые задачи.
|
||
h.completeUpdate();
|
||
await settle();
|
||
});
|
||
|
||
// 3. Отказ регистрации не превращает успешный Ping в disconnected.
|
||
test('Ошибка SW update: connected не меняется, ошибка безопасно экспортируется', async () => {
|
||
const h = harness({ swError: true });
|
||
await h.health();
|
||
await settle();
|
||
assert.equal(operation(h, 'sw_registration_update').outcome, 'error');
|
||
assert.equal(operation(h, 'sw_registration_update').errorType, 'NetworkError');
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
assert.equal(count(h, 'request'), 1);
|
||
assert.doesNotMatch(JSON.stringify(h.exportData()), /secret|token|https?:|sessionId/);
|
||
});
|
||
|
||
// 4. Новый Ping может выполняться во время SW; одноразовый guard не позволяет начать второй SW update.
|
||
test('Повторный Ping при незавершённом SW: два Ping, но строго один first_ping update', async () => {
|
||
const h = harness({ slowSw: true });
|
||
await h.health();
|
||
await h.health();
|
||
assert.equal(count(h, 'request'), 2);
|
||
assert.equal(count(h, 'sw-update'), 1);
|
||
assert.equal(count(h, 'sw-list'), 1);
|
||
assert.equal(count(h, 'splash-class'), 1);
|
||
assert.equal(count(h, 'timer'), 1);
|
||
assert.equal(h.exportData().counters.pingStarted, 2);
|
||
assert.equal(h.exportData().splashTrace.operations.filter(x => x.operation === 'pwa_first_ping_update').length, 1);
|
||
h.completeUpdate();
|
||
await settle();
|
||
});
|
||
|
||
// 5. reconnect не отменяет ранее стартовавший SW и его завершение не меняет состояние.
|
||
test('WS reconnect во время обновления: повторный Ping один, старое SW-завершение не меняет статус', async () => {
|
||
const h = harness({ slowSw: true });
|
||
await h.health();
|
||
h.disconnect();
|
||
await h.health();
|
||
assert.equal(count(h, 'ws-open'), 1);
|
||
assert.equal(count(h, 'ws-restore'), 1);
|
||
assert.equal(count(h, 'request'), 2);
|
||
assert.equal(count(h, 'sw-update'), 1);
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
h.completeUpdate();
|
||
await settle();
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
assert.equal(count(h, 'splash-class'), 1);
|
||
});
|
||
|
||
test('Позднее завершение SW не возвращает connected после нового неудачного Ping', async () => {
|
||
const h = harness({ slowSw: true });
|
||
await h.health();
|
||
h.failNextPing();
|
||
await h.health();
|
||
assert.equal(h.context.connectionState, 'disconnected');
|
||
assert.equal(count(h, 'request'), 2);
|
||
assert.equal(count(h, 'sw-update'), 1);
|
||
h.completeUpdate();
|
||
await settle();
|
||
assert.equal(h.context.connectionState, 'disconnected');
|
||
assert.equal(count(h, 'request'), 2);
|
||
assert.equal(count(h, 'splash-class'), 1);
|
||
});
|
||
|
||
test('Завершение SW после смены профиля не изменяет session и connection state', async () => {
|
||
const h = harness({ slowSw: true });
|
||
await h.health();
|
||
// Имитируем уже проведённый внешним lifecycle переход профиля/logout.
|
||
h.context.state.session.isAuthorized = false;
|
||
h.context.state.session.profileMarker = 'new-profile';
|
||
h.context.connectionState = 'disconnected';
|
||
h.completeUpdate();
|
||
await settle();
|
||
assert.equal(h.context.state.session.isAuthorized, false);
|
||
assert.equal(h.context.state.session.profileMarker, 'new-profile');
|
||
assert.equal(h.context.connectionState, 'disconnected');
|
||
assert.equal(count(h, 'request'), 1);
|
||
});
|
||
|
||
// 6. Проверка версии по-прежнему планирует reload и запускает отдельный reload-SW путь.
|
||
test('Параллельная проверка версии UI: обновление и reload работают при pending first_ping SW', async () => {
|
||
const h = harness({ slowSw: true, remoteHash: 'new', hostHash: 'new' });
|
||
await h.health();
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
await settle();
|
||
assert.equal(count(h, 'ui-version-fetch'), 1);
|
||
assert.equal(h.context.uiUpdateReloadScheduled, true);
|
||
assert.equal(h.context.connectionState, 'updating');
|
||
assert.equal(h.timers.filter(x => x.milliseconds === 600).length, 1);
|
||
assert.equal(count(h, 'request'), 1);
|
||
assert.equal(h.exportData().splashTrace.operations.filter(x => x.operation === 'sw_refresh' && x.context === 'first_ping').length, 1);
|
||
assert.equal(h.exportData().splashTrace.operations.filter(x => x.operation === 'sw_refresh' && x.context === 'reload').length, 1);
|
||
h.completeUpdate();
|
||
await settle();
|
||
assert.equal(h.context.connectionState, 'updating');
|
||
h.timers.find(t => t.milliseconds === 600).callback();
|
||
assert.equal(count(h, 'reload'), 1);
|
||
});
|
||
|
||
// 7. Отсутствие serviceWorker в navigator совместимо с non-blocking веткой.
|
||
test('Нет Service Worker API: нет SW-операций, Ping и закрытие Splash остаются', async () => {
|
||
const h = harness({ swSupported: false });
|
||
await h.health();
|
||
await settle();
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
assert.equal(count(h, 'sw-update'), 0);
|
||
assert.equal(count(h, 'request'), 1);
|
||
assert.equal(count(h, 'splash-class'), 1);
|
||
assert.equal(operation(h, 'sw_refresh'), undefined);
|
||
assert.equal(operation(h, 'pwa_first_ping_update').outcome, 'ok');
|
||
});
|
||
|
||
// 8. Guard работает на один запуск документа: после реального page reload создаётся новый контекст.
|
||
test('Повторная загрузка страницы PWA: ровно один update на каждую страницу', async () => {
|
||
const firstPage = harness();
|
||
await firstPage.health();
|
||
await firstPage.health();
|
||
await settle();
|
||
assert.equal(count(firstPage, 'request'), 2);
|
||
assert.equal(count(firstPage, 'sw-update'), 1);
|
||
const nextPage = harness();
|
||
await nextPage.health();
|
||
await settle();
|
||
assert.equal(count(nextPage, 'request'), 1);
|
||
assert.equal(count(nextPage, 'sw-update'), 1);
|
||
assert.equal(nextPage.exportData().splashTrace.operations.filter(x => x.operation === 'pwa_first_ping_update').length, 1);
|
||
});
|
||
|
||
// Обработка исключения SW-задачи независима от успешного Ping.
|
||
test('Неожиданный reject SW-задачи обработан, status остаётся connected', async () => {
|
||
const h = harness();
|
||
runInNewContext("tryUpdatePwaOnFirstConnectedPing = async () => { throw new Error('private reject'); };", h.context);
|
||
await h.health();
|
||
await settle();
|
||
assert.equal(h.context.connectionState, 'connected');
|
||
assert.equal(count(h, 'splash-class'), 1);
|
||
});
|
||
|
||
// Контроль минимальности: восстановление старой await-строки внутри того же источника.
|
||
test('Контроль Stage 0.1 и Stage 1.1: один health-check не создаёт новых Ping/WS/SW/timers', async () => {
|
||
const pattern = / \/\/ Проверка SW остаётся одноразовой[^\n]*\n void tryUpdatePwaOnFirstConnectedPing\(\)\.catch\(\(\) => \{\n \/\/ Ошибка уже отмечена[^\n]*\n \}\);\n setConnectionStatus\('connected'\);/;
|
||
assert.match(appSource, pattern);
|
||
const controlSource = appSource.replace(pattern, " await tryUpdatePwaOnFirstConnectedPing();\n setConnectionStatus('connected');");
|
||
const before = harness({ source: controlSource });
|
||
const after = harness();
|
||
await before.health();
|
||
await after.health();
|
||
await settle();
|
||
const effects = ['request', 'ws-open', 'ws-restore', 'sw-list', 'sw-update', 'timer', 'splash-class'];
|
||
for (const kind of effects) assert.equal(count(before, kind), count(after, kind), kind);
|
||
const networkAndWorker = ['request', 'ws-open', 'ws-restore', 'sw-list', 'sw-update'];
|
||
assert.deepEqual(before.log.filter(x => networkAndWorker.includes(x[0])).map(x => x[0]),
|
||
after.log.filter(x => networkAndWorker.includes(x[0])).map(x => x[0]));
|
||
assert.equal(before.context.connectionState, after.context.connectionState);
|
||
});
|