SHA256
Доработать диагностику запуска UI
This commit is contained in:
@@ -0,0 +1,350 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
|
||||
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||||
const app = readFileSync(new URL('../js/app.js', import.meta.url), 'utf8');
|
||||
const diagnosticScript = html.match(/<script id="shine-stage0-startup-diagnostics">([\s\S]*?)<\/script>/)?.[1];
|
||||
assert.ok(diagnosticScript, 'Must extend the original inline Stage 0 diagnostic; no extra scripts');
|
||||
|
||||
export function diagnosticHarness(debug = '1') {
|
||||
const marks = [];
|
||||
let time = 100;
|
||||
const performance = {
|
||||
now: () => { time += 0.7; return time; },
|
||||
mark: (name) => marks.push(name),
|
||||
getEntriesByType: () => [],
|
||||
};
|
||||
const window = { performance };
|
||||
runInNewContext(diagnosticScript, {
|
||||
window, performance,
|
||||
localStorage: { getItem: () => debug },
|
||||
document: { addEventListener() {} },
|
||||
fetch() { throw Error('Unexpected fetch by diagnostic'); },
|
||||
WebSocket: class { constructor() { throw Error('Unexpected socket by diagnostic'); } },
|
||||
setTimeout() { throw Error('Unexpected timeout by diagnostic'); },
|
||||
setInterval() { throw Error('Unexpected interval by diagnostic'); },
|
||||
});
|
||||
return { trace: window.__SHINE_STAGE0__, exportData: () => JSON.parse(window.__SHINE_STAGE0_EXPORT__()), marks, window };
|
||||
}
|
||||
|
||||
// Standalone source slices from the real app, without imports or network access.
|
||||
// Preserves actual function bodies so these are not reimplementations of Ping/Splash.
|
||||
const functionSlices = [
|
||||
['function finishInitialConnectionSplash()', 'function startConnectionCountdown()'],
|
||||
['function setConnectionStatus(', 'async function triggerImmediateConnectionRetry()'],
|
||||
['function extractBuildHashFromHtml(', 'function startPeriodicUiVersionCheck()'],
|
||||
['async function checkConnectionHealth(', 'function startConnectionMonitor('],
|
||||
];
|
||||
export function extractSplashChain(source = app) {
|
||||
return functionSlices.map(([start, stop]) => {
|
||||
const from = source.indexOf(start);
|
||||
const until = source.indexOf(stop, from + start.length);
|
||||
assert.ok(from !== -1 && until > from, `Missing source slice: ${start}`);
|
||||
return source.slice(from, until);
|
||||
}).join('\n');
|
||||
}
|
||||
|
||||
export function appHarness({ source = app, debug = true, sw = 'one', pingError = null, remoteHash = 'same', hostHash = 'same', wsOpen = true, awaitUpdate = false, awaitPing = false, fetchOk = true } = {}) {
|
||||
const log = [];
|
||||
const timers = [];
|
||||
const eventHandlers = new Map();
|
||||
const { window, exportData } = debug ? diagnosticHarness() : { window: {}, exportData: () => null };
|
||||
let resolvePing;
|
||||
const pingGate = awaitPing ? new Promise(resolve => { resolvePing = resolve; }) : null;
|
||||
let isWsOpen = wsOpen;
|
||||
let resolveUpdate;
|
||||
const updateGate = awaitUpdate ? new Promise(resolve => { resolveUpdate = resolve; }) : null;
|
||||
const element = {
|
||||
classList: { add: (...args) => log.push(['splash-class', ...args]) },
|
||||
addEventListener: (name, callback) => {
|
||||
log.push(['listener', name]);
|
||||
eventHandlers.set(name, callback);
|
||||
},
|
||||
remove: () => log.push(['splash-remove']),
|
||||
};
|
||||
const serviceWorker = sw === 'none' ? undefined : {
|
||||
getRegistrations: async () => {
|
||||
log.push(['sw-list']);
|
||||
if (sw === 'list-error') throw Object.assign(new Error('TOP_SECRET'), { name: 'SecurityError' });
|
||||
return sw === 'empty' ? [] : [
|
||||
{ update: async () => {
|
||||
log.push(['sw-update']);
|
||||
if (updateGate) await updateGate;
|
||||
if (sw === 'update-error') throw Object.assign(new Error('TOKEN_PII'), { name: 'NetworkError' });
|
||||
}, waiting: sw === 'waiting' ? { postMessage(value) { log.push(['sw-post-message', value.type]); } } : null },
|
||||
];
|
||||
},
|
||||
};
|
||||
const navigator = sw === 'none' ? {} : { serviceWorker };
|
||||
window.setTimeout = (fn, ms) => { log.push(['timeout', ms]); timers.push(fn); };
|
||||
window.location = { reload() { log.push(['reload']); } };
|
||||
const context = {
|
||||
window,
|
||||
navigator, initialSplashEl: element, initialConnectionCompleted: false,
|
||||
connectionState: '', connectionStatusText: '', connectionNextRetryAtMs: 0,
|
||||
CONNECTION_CHECK_INTERVAL_MS: 20000,
|
||||
connectionCheckInFlight: false, uiVersionCheckInFlight: false, pwaUpdateCheckAttempted: false,
|
||||
uiUpdateReloadScheduled: false,
|
||||
state: { session: { isLocalDemo: false } },
|
||||
wsIsOpen: () => isWsOpen,
|
||||
authService: { ws: {
|
||||
async open() { log.push(['ws-open']); isWsOpen = true; },
|
||||
async request(op) { log.push(['request', op]); if (pingGate) await pingGate; if (pingError) throw pingError; return { uiBuildHash: remoteHash }; },
|
||||
} },
|
||||
ensureSessionAfterWsReconnect: async () => { log.push(['reconnect-restore']); return true; },
|
||||
stopConnectionCountdown: () => log.push(['stop-countdown']),
|
||||
startConnectionCountdown: () => log.push(['start-countdown']),
|
||||
refreshConnectionUi: () => log.push(['refresh-connection-ui']),
|
||||
CURRENT_BUILD_HASH: 'same', UI_BUILD_HASH_PATTERN: /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/,
|
||||
fetch: async () => { log.push(['version-fetch']); return { ok: fetchOk, async text() { return `window.__SHINE_BUILD_HASH__ = '${hostHash}'`; } }; },
|
||||
addAppLogEntry: () => log.push(['log-entry']),
|
||||
};
|
||||
runInNewContext(extractSplashChain(source), context);
|
||||
return {
|
||||
context, log, timers, resolveUpdate, resolvePing, exportData, eventHandlers,
|
||||
setWsOpen(value) { isWsOpen = value; },
|
||||
async run() { await runInNewContext('checkConnectionHealth()', context); },
|
||||
};
|
||||
}
|
||||
|
||||
test('Stage 0 keeps its export and Stage 0.1 adds bounded, paired operation measurements', () => {
|
||||
const { trace, exportData, marks } = diagnosticHarness();
|
||||
trace.mark('first_dom_render');
|
||||
const ping = trace.begin('ping');
|
||||
assert.equal(exportData().splashTrace.operations[0].durationMs, null);
|
||||
assert.equal(exportData().splashTrace.operations[0].outcome, 'pending');
|
||||
trace.finish(ping);
|
||||
trace.mark('splash_leave');
|
||||
const exported = exportData();
|
||||
assert.equal(exported.schema, 'shine-stage0-v1');
|
||||
assert.ok(exported.timing.first_dom_render);
|
||||
assert.ok(exported.durations.renderToSplashLeaveMs > 0);
|
||||
assert.ok(exported.splashTrace.operations[0].durationMs > 0);
|
||||
assert.equal(exported.splashTrace.operations[0].outcome, 'ok');
|
||||
assert.ok(marks.includes('shine-stage0:ping:start'));
|
||||
assert.ok(marks.includes('shine-stage0:ping:end'));
|
||||
assert.equal(exported.counters.pingStarted, 1);
|
||||
assert.equal(exported.counters.pingCompleted, 1);
|
||||
});
|
||||
|
||||
test('Absent operations are missing rather than a zero-duration SW/version/ping measurement', () => {
|
||||
const { exportData } = diagnosticHarness();
|
||||
const result = exportData();
|
||||
assert.deepEqual(result.splashTrace.operations, []);
|
||||
assert.equal(result.durations.splashTransitionToRemovalMs, null);
|
||||
assert.equal(result.counters.pingStarted, 0);
|
||||
});
|
||||
|
||||
test('Untrusted strings, error messages, URLs and tokens cannot enter diagnostic JSON', () => {
|
||||
const { trace, exportData } = diagnosticHarness();
|
||||
trace.mark('SECRET_URL_TOKEN');
|
||||
assert.equal(trace.begin('SECRET_URL_TOKEN'), null);
|
||||
const id = trace.begin('sw_registration_update');
|
||||
trace.finish(id, 'error', { name: 'TokenBearerSECRET', message: 'https://secret/?sessionId=abc' });
|
||||
const errId = trace.begin('ping');
|
||||
trace.finish(errId, 'error', { name: 'SecurityError', payload: { token: 'SECRET' } });
|
||||
const json = JSON.stringify(exportData());
|
||||
assert.doesNotMatch(json, /SECRET|https?:|sessionId|token/);
|
||||
assert.equal(exportData().splashTrace.operations[0].errorType, 'UnknownError');
|
||||
assert.equal(exportData().splashTrace.operations[1].errorType, 'SecurityError');
|
||||
});
|
||||
|
||||
test('Interleaved registration updates match their own start/end, not FIFO completion', () => {
|
||||
const { trace, exportData } = diagnosticHarness();
|
||||
const a = trace.begin('sw_registration_update');
|
||||
const b = trace.begin('sw_registration_update');
|
||||
trace.finish(b);
|
||||
trace.finish(a, 'error', { name: 'NetworkError', message: 'PRIVATE' });
|
||||
const [first, second] = exportData().splashTrace.operations;
|
||||
assert.ok(first.durationMs > second.durationMs);
|
||||
assert.equal(first.outcome, 'error');
|
||||
assert.equal(first.errorType, 'NetworkError');
|
||||
assert.equal(second.outcome, 'ok');
|
||||
});
|
||||
|
||||
test('Operation cap bounds memory; Stage 0 event cap and original export still work', () => {
|
||||
const { trace, exportData } = diagnosticHarness();
|
||||
for (let i = 0; i < 300; i++) {
|
||||
const id = trace.begin('ping');
|
||||
trace.finish(id);
|
||||
}
|
||||
for (let i = 0; i < 300; i++) trace.mark('ws_attempt');
|
||||
const result = exportData();
|
||||
assert.equal(result.splashTrace.operations.length, 256);
|
||||
assert.equal(result.counters.operationsDropped, 44);
|
||||
assert.equal(result.counters.wsAttempts, 300);
|
||||
assert.equal(result.events.length, 256);
|
||||
});
|
||||
|
||||
test('Successful Ping connects and starts Splash before the existing SW update finishes', async () => {
|
||||
const h = appHarness({ awaitUpdate: true });
|
||||
await h.run();
|
||||
assert.equal(h.context.connectionState, 'connected');
|
||||
assert.deepEqual(h.log.filter(([name]) => name === 'request').map(([, op]) => op), ['Ping']);
|
||||
assert.equal(h.log.filter(([name]) => name === 'splash-class').length, 1);
|
||||
assert.equal(h.timers.length, 1);
|
||||
const stages = h.exportData().events.map(({ stage }) => stage);
|
||||
assert.ok(stages.indexOf('status_connected') < stages.indexOf('splash_finish_called'));
|
||||
assert.ok(stages.indexOf('splash_finish_called') < stages.indexOf('splash_leave'));
|
||||
const ops = h.exportData().splashTrace.operations;
|
||||
const ping = ops.find(op => op.operation === 'ping');
|
||||
const pwa = ops.find(op => op.operation === 'pwa_first_ping_update');
|
||||
assert.equal(ping.outcome, 'ok');
|
||||
assert.equal(pwa.outcome, 'pending');
|
||||
assert.ok(ping.endMs <= pwa.startMs);
|
||||
assert.equal(ops.find(op => op.operation === 'sw_registration_update').endMs, null);
|
||||
h.resolveUpdate();
|
||||
for (let i = 0; i < 12; i++) await Promise.resolve();
|
||||
const finished = h.exportData().splashTrace.operations.find(op => op.operation === 'pwa_first_ping_update');
|
||||
assert.equal(finished.outcome, 'ok');
|
||||
assert.ok(h.exportData().timing.status_connected < finished.endMs);
|
||||
});
|
||||
|
||||
test('CSS transitionstart is measured independently; timeout removal retains original timer', async () => {
|
||||
const h = appHarness();
|
||||
await h.run();
|
||||
const stageBefore = h.exportData();
|
||||
assert.ok(stageBefore.timing.splash_leave);
|
||||
assert.equal(stageBefore.timing.splash_transition_start, undefined);
|
||||
const handler = h.eventHandlers.get('transitionstart');
|
||||
assert.equal(typeof handler, 'function');
|
||||
handler({ target: {}, propertyName: 'opacity' });
|
||||
assert.equal(h.exportData().timing.splash_transition_start, undefined);
|
||||
handler({ target: h.context.initialSplashEl, propertyName: 'opacity' });
|
||||
assert.ok(h.exportData().timing.splash_transition_start);
|
||||
h.timers[0]();
|
||||
const result = h.exportData();
|
||||
assert.ok(result.timing.splash_removed);
|
||||
assert.ok(result.timing.splash_removed_via_timeout);
|
||||
assert.equal(result.timing.splash_removed_via_transition, undefined);
|
||||
assert.equal(h.log.filter(([name]) => name === 'splash-remove').length, 1);
|
||||
});
|
||||
|
||||
test('No SW support: no SW operations; Ping and Splash still run', async () => {
|
||||
const h = appHarness({ sw: 'none' });
|
||||
await h.run();
|
||||
assert.equal(h.log.filter(([name]) => name === 'sw-list').length, 0);
|
||||
assert.equal(h.log.filter(([name]) => name === 'request').length, 1);
|
||||
assert.ok(!h.exportData().splashTrace.operations.some(op => op.operation.startsWith('sw_')));
|
||||
assert.ok(h.exportData().splashTrace.operations.some(op => op.operation === 'pwa_first_ping_update'));
|
||||
assert.equal(h.context.connectionState, 'connected');
|
||||
});
|
||||
|
||||
test('Ping failure records a safe type and does not start PWA update or Splash', async () => {
|
||||
const err = Object.assign(new Error('secret token'), { name: 'NetworkError' });
|
||||
const h = appHarness({ pingError: err });
|
||||
await h.run();
|
||||
const ops = h.exportData().splashTrace.operations;
|
||||
assert.equal(ops.find(op => op.operation === 'ping').errorType, 'NetworkError');
|
||||
assert.equal(ops.find(op => op.operation === 'connection_health').outcome, 'error');
|
||||
assert.ok(!ops.some(op => op.operation.startsWith('sw_') || op.operation === 'pwa_first_ping_update'));
|
||||
assert.equal(h.context.connectionState, 'disconnected');
|
||||
assert.equal(h.log.some(([name]) => name === 'splash-class'), false);
|
||||
assert.doesNotMatch(JSON.stringify(h.exportData()), /secret token/);
|
||||
});
|
||||
|
||||
test('Existing SW errors are swallowed as before, but have a safe error class', async () => {
|
||||
const h = appHarness({ sw: 'update-error' });
|
||||
await h.run();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
const update = h.exportData().splashTrace.operations.find(op => op.operation === 'sw_registration_update');
|
||||
assert.equal(update.outcome, 'error');
|
||||
assert.equal(update.errorType, 'NetworkError');
|
||||
assert.equal(h.context.connectionState, 'connected');
|
||||
});
|
||||
|
||||
test('UI version check only exists on differing Ping hashes and never blocks connected status', async () => {
|
||||
const h = appHarness({ remoteHash: 'other' });
|
||||
await h.run();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
const ops = h.exportData().splashTrace.operations;
|
||||
assert.ok(ops.some(op => op.operation === 'ui_version_ping' && op.outcome === 'ok'));
|
||||
assert.ok(ops.some(op => op.operation === 'ui_version_fetch' && op.outcome === 'ok'));
|
||||
assert.equal(h.log.filter(([name]) => name === 'version-fetch').length, 1);
|
||||
assert.equal(h.context.connectionState, 'connected');
|
||||
const ordinary = appHarness({ remoteHash: 'same' });
|
||||
await ordinary.run();
|
||||
assert.equal(ordinary.log.filter(([name]) => name === 'version-fetch').length, 0);
|
||||
assert.ok(!ordinary.exportData().splashTrace.operations.some(op => op.operation.startsWith('ui_version')));
|
||||
});
|
||||
|
||||
test('Stage 0.1 only uses the existing inline module, no new Ping/WS/fetch/timers in the measurement layer', () => {
|
||||
assert.doesNotMatch(diagnosticScript, /new WebSocket|\.send\(|\bfetch\(|\.request\(|setTimeout|setInterval|\.postMessage\(|\.register\(/);
|
||||
assert.doesNotMatch(diagnosticScript, /\.url|\.message|\.payload|\.sessionId/);
|
||||
assert.match(app, /const pingResp = await authService\.ws\.request\('Ping', \{ ts: Date\.now\(\) \}, 7000\)/);
|
||||
assert.match(app, /window\.setTimeout\(removeSplash, 700\)/);
|
||||
assert.match(app, /void tryUpdatePwaOnFirstConnectedPing\(\)\.catch\(/);
|
||||
});
|
||||
|
||||
test('Repeated health invocation during a pending Ping adds no second Ping or SW update', async () => {
|
||||
const h = appHarness({ awaitPing: true });
|
||||
const first = h.run();
|
||||
for (let i = 0; i < 12; i++) await Promise.resolve();
|
||||
await h.run();
|
||||
assert.equal(h.log.filter(([name, op]) => name === 'request' && op === 'Ping').length, 1);
|
||||
assert.equal(h.exportData().events.filter(e => e.stage === 'health_skipped_inflight').length, 1);
|
||||
h.resolvePing();
|
||||
await first;
|
||||
for (let i = 0; i < 5; i++) await Promise.resolve();
|
||||
assert.equal(h.log.filter(([name]) => name === 'sw-update').length, 1);
|
||||
assert.equal(h.exportData().splashTrace.operations.filter(op => op.operation === 'connection_health').length, 1);
|
||||
});
|
||||
|
||||
test('Local demo records health invocation but must not run Ping, SW refresh or PWA update', async () => {
|
||||
const h = appHarness();
|
||||
h.context.state.session.isLocalDemo = true;
|
||||
await h.run();
|
||||
assert.equal(h.log.filter(([name]) => name === 'request' || name.startsWith('sw-')).length, 0);
|
||||
assert.equal(h.context.connectionState, 'connected');
|
||||
const result = h.exportData();
|
||||
assert.ok(result.events.some(e => e.stage === 'health_local_demo'));
|
||||
assert.equal(result.splashTrace.operations.filter(op => op.operation === 'connection_health').length, 1);
|
||||
assert.equal(result.splashTrace.operations.filter(op => op.operation === 'ping').length, 0);
|
||||
});
|
||||
|
||||
test('Stage 0.1 calls remain safe if cached Stage 0 bootstrap lacks begin/finish methods', async () => {
|
||||
const h = appHarness({ debug: false });
|
||||
h.context.window.__SHINE_STAGE0__ = { mark() {} };
|
||||
await h.run();
|
||||
assert.equal(h.log.filter(([name, op]) => name === 'request' && op === 'Ping').length, 1);
|
||||
assert.equal(h.context.connectionState, 'connected');
|
||||
assert.equal(h.timers.length, 1);
|
||||
});
|
||||
|
||||
test('Transitionend removal records source once even if the existing timeout later fires', async () => {
|
||||
const h = appHarness();
|
||||
await h.run();
|
||||
h.eventHandlers.get('transitionend')({ type: 'transitionend', target: h.context.initialSplashEl });
|
||||
assert.ok(h.exportData().timing.splash_removed_via_transition);
|
||||
h.timers[0]();
|
||||
assert.equal(h.exportData().timing.splash_removed_via_timeout, undefined);
|
||||
assert.equal(h.exportData().events.filter(e => e.stage === 'splash_removed').length, 1);
|
||||
// The original code also invokes remove() twice; this diagnostic does not prevent it.
|
||||
assert.equal(h.log.filter(([name]) => name === 'splash-remove').length, 2);
|
||||
});
|
||||
|
||||
test('A non-OK UI version probe has a fixed, non-sensitive error type, while connected remains unchanged', async () => {
|
||||
const h = appHarness({ remoteHash: 'other', fetchOk: false });
|
||||
await h.run();
|
||||
for (let i = 0; i < 4; i++) await Promise.resolve();
|
||||
const probe = h.exportData().splashTrace.operations.find(op => op.operation === 'ui_version_fetch');
|
||||
assert.equal(probe.outcome, 'error');
|
||||
assert.equal(probe.errorType, 'HttpResponseNotOk');
|
||||
assert.equal(h.context.connectionState, 'connected');
|
||||
});
|
||||
|
||||
test('SW waiting.postMessage trace is absent during the first Ping and measured on existing reload path', async () => {
|
||||
const h = appHarness({ sw: 'waiting' });
|
||||
await h.run();
|
||||
assert.equal(h.log.filter(([name]) => name === 'sw-post-message').length, 0);
|
||||
assert.equal(h.exportData().splashTrace.operations.filter(op => op.operation === 'sw_skip_waiting').length, 0);
|
||||
await runInNewContext('refreshServiceWorkers({ activateWaitingWorker: true })', h.context);
|
||||
assert.equal(h.log.filter(([name]) => name === 'sw-post-message').length, 1);
|
||||
const result = h.exportData();
|
||||
const posted = result.splashTrace.operations.find(op => op.operation === 'sw_skip_waiting');
|
||||
assert.equal(posted.outcome, 'ok');
|
||||
assert.equal(posted.context, 'reload');
|
||||
assert.equal(result.splashTrace.operations.find(op => op.operation === 'sw_refresh').context, 'first_ping');
|
||||
});
|
||||
@@ -0,0 +1,110 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { runInNewContext } from 'node:vm';
|
||||
|
||||
const html = readFileSync(new URL('../index.html', import.meta.url), 'utf8');
|
||||
const block = html.match(/<script id="shine-stage0-startup-diagnostics">([\s\S]*?)<\/script>/);
|
||||
assert.ok(block, 'Диагностический загрузчик должен быть встроен без нового сетевого запроса');
|
||||
const script = block[1];
|
||||
|
||||
function createHarness(flag) {
|
||||
const listeners = new Map();
|
||||
const marks = [];
|
||||
let tick = 10;
|
||||
const performance = {
|
||||
mark: (name) => marks.push(name),
|
||||
now: () => ++tick,
|
||||
getEntriesByType: (type) => type === 'navigation'
|
||||
? [{ domContentLoadedEventEnd: 120 }]
|
||||
: type === 'paint' ? [{ name: 'first-contentful-paint', startTime: 240 }] : [],
|
||||
};
|
||||
const window = { performance };
|
||||
const sandbox = {
|
||||
window, performance,
|
||||
localStorage: { getItem(key) { assert.equal(key, 'shine-feature-developer-tools-v1'); return flag; } },
|
||||
document: { addEventListener(event, handler) { listeners.set(event, handler); } },
|
||||
WebSocket: class { constructor() { throw Error('не должен создаваться'); } },
|
||||
setInterval() { throw Error('не должен запускаться интервал'); },
|
||||
setTimeout() { throw Error('не должен запускаться таймер'); },
|
||||
};
|
||||
runInNewContext(script, sandbox);
|
||||
return { window, listeners, marks };
|
||||
}
|
||||
|
||||
test('без debug флага нет активного измерителя, экспорта и побочных действий', () => {
|
||||
for (const flag of [null, '0', 'false', '']) {
|
||||
const { window, listeners, marks } = createHarness(flag);
|
||||
assert.equal(window.__SHINE_STAGE0__, undefined);
|
||||
assert.equal(window.__SHINE_STAGE0_EXPORT__, undefined);
|
||||
assert.equal(listeners.size, 0);
|
||||
assert.equal(marks.length, 0);
|
||||
}
|
||||
});
|
||||
|
||||
test('в debug режиме фиксируются Performance marks и DOM ready, экспорт является валидным JSON', () => {
|
||||
const { window, listeners, marks } = createHarness('1');
|
||||
assert.equal(typeof window.__SHINE_STAGE0_EXPORT__, 'function');
|
||||
assert.ok(marks.includes('shine-stage0:bootstrap'));
|
||||
listeners.get('DOMContentLoaded')();
|
||||
window.__SHINE_STAGE0__.mark('css_start');
|
||||
window.__SHINE_STAGE0__.mark('css_ok');
|
||||
window.__SHINE_STAGE0__.mark('css_error');
|
||||
window.__SHINE_STAGE0__.mark('css_complete');
|
||||
window.__SHINE_STAGE0__.mark('ws_attempt');
|
||||
window.__SHINE_STAGE0__.mark('ws_attempt');
|
||||
window.__SHINE_STAGE0__.mark('ws_open');
|
||||
window.__SHINE_STAGE0__.mark('first_dom_render');
|
||||
window.__SHINE_STAGE0__.mark('session_restore_start');
|
||||
window.__SHINE_STAGE0__.mark('session_restore_ok');
|
||||
const result = JSON.parse(window.__SHINE_STAGE0_EXPORT__());
|
||||
assert.equal(result.schema, 'shine-stage0-v1');
|
||||
assert.equal(result.counters.cssLoaded, 1);
|
||||
assert.equal(result.counters.cssFailed, 1);
|
||||
assert.equal(result.counters.wsAttempts, 2);
|
||||
assert.equal(result.counters.wsAttemptsAfterFirst, 1);
|
||||
assert.equal(result.counters.wsOpened, 1);
|
||||
assert.equal(result.browser.domContentLoadedMs, 120);
|
||||
assert.equal(result.browser.firstContentfulPaintMs, 240);
|
||||
assert.ok(result.durations.cssAllSettledMs > 0);
|
||||
assert.ok(result.events.every((e) => /^[-a-z_]+$/.test(e.stage) && Number.isFinite(e.atMs)));
|
||||
});
|
||||
|
||||
test('метрики не принимают секреты, произвольные этапы или повторные однократные события', () => {
|
||||
const { window, marks } = createHarness('true');
|
||||
const token = 'SECRET_token_sessionId_login_url';
|
||||
window.__SHINE_STAGE0__.mark(token);
|
||||
window.__SHINE_STAGE0__.mark('bootstrap');
|
||||
window.__SHINE_STAGE0__.mark('ws_error');
|
||||
window.__SHINE_STAGE0__.mark('ws_error');
|
||||
const json = window.__SHINE_STAGE0_EXPORT__();
|
||||
assert.ok(!json.includes(token));
|
||||
assert.equal(marks.filter((name) => name === 'shine-stage0:bootstrap').length, 1);
|
||||
assert.equal(JSON.parse(json).counters.wsOpenErrors, 2);
|
||||
assert.ok(!/wss?:\/\//.test(json));
|
||||
});
|
||||
|
||||
test('ограничен объём событий, счётчики продолжают учитывать попытки без URL', () => {
|
||||
const { window, marks } = createHarness('1');
|
||||
for (let i = 0; i < 500; i++) window.__SHINE_STAGE0__.mark('ws_attempt');
|
||||
const result = JSON.parse(window.__SHINE_STAGE0_EXPORT__());
|
||||
assert.equal(result.counters.wsAttempts, 500);
|
||||
assert.ok(result.events.length <= 256);
|
||||
assert.ok(marks.length <= 256);
|
||||
assert.equal(result.counters.eventsDropped, 245);
|
||||
});
|
||||
|
||||
test('инструмент не подменяет WebSocket, fetch, Push, роуты, Ping и не запускает таймеры', () => {
|
||||
assert.doesNotMatch(script, /new WebSocket|\.send\(|\bfetch\(|serviceWorker|setTimeout|setInterval|pushManager|location\.assign/);
|
||||
assert.doesNotMatch(script, /sessionId|storagePwd|password|token|requestId|authorization|\.url/);
|
||||
});
|
||||
|
||||
test('после успешного resume ошибка последующего запроса не маркируется ошибкой восстановления', () => {
|
||||
const { window } = createHarness('1');
|
||||
window.__SHINE_STAGE0__.mark('session_restore_start');
|
||||
window.__SHINE_STAGE0__.mark('session_restore_ok');
|
||||
window.__SHINE_STAGE0__.mark('session_restore_failed');
|
||||
const result = JSON.parse(window.__SHINE_STAGE0_EXPORT__());
|
||||
assert.equal(result.counters.sessionRestoreFailures, 0);
|
||||
assert.equal(result.durations.sessionRestoreMs, 1);
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
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);
|
||||
});
|
||||
@@ -0,0 +1,282 @@
|
||||
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');
|
||||
});
|
||||
Reference in New Issue
Block a user