Files
SHiNE-server/shine-UI/tests/stage0-1-splash-trace.test.mjs

351 lines
18 KiB
JavaScript

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');
});