Доработать диагностику запуска UI

This commit is contained in:
2026-10-23 11:22:33 +03:00
parent df0e9cef9b
commit dbac798e7f
8 changed files with 1349 additions and 24 deletions
+177 -2
View File
@@ -12,6 +12,175 @@
<link rel="icon" type="image/jpeg" href="./img/logo.jpg" />
<link rel="apple-touch-icon" href="./img/logo.jpg" />
<title>СИЯНИЕ</title>
<script id="shine-stage0-startup-diagnostics">
// Stage 0: пассивные метки только при включённых инструментах разработчика.
(function initializeStartupDiagnostics() {
let debugEnabled = false;
try {
const flag = localStorage.getItem('shine-feature-developer-tools-v1');
debugEnabled = flag === '1' || flag === 'true';
} catch {}
if (!debugEnabled || !window.performance || typeof performance.mark !== 'function') return;
const allowed = new Set([
'bootstrap', 'dom_ready', 'css_start', 'css_ok', 'css_error', 'css_complete', 'css_revealed',
'main_js_requested', 'main_js_start', 'first_dom_render', 'splash_leave', 'splash_removed',
'ws_attempt', 'ws_open', 'ws_error', 'ws_close',
'session_restore_start', 'session_restore_ok', 'session_restore_failed',
'reconnect_restore_start', 'reconnect_restore_ok', 'reconnect_restore_failed',
'health_invoked', 'health_skipped_inflight', 'health_local_demo',
'status_connected', 'splash_finish_called', 'splash_transition_start',
'splash_removed_via_transition', 'splash_removed_via_timeout',
]);
const single = new Set([
'bootstrap', 'dom_ready', 'css_start', 'css_complete', 'css_revealed',
'main_js_requested', 'main_js_start', 'first_dom_render', 'splash_leave', 'splash_removed',
'session_restore_start', 'session_restore_ok', 'session_restore_failed',
'splash_transition_start', 'splash_removed_via_transition', 'splash_removed_via_timeout',
]);
const operationsAllowed = new Set([
'connection_health', 'monitor_start', 'ping', 'pwa_first_ping_update', 'ui_version_ping',
'ui_version_periodic', 'ui_version_fetch', 'sw_refresh',
'sw_get_registrations', 'sw_registration_update', 'sw_skip_waiting',
]);
const operationContexts = new Set([
'first_ping', 'reload', 'bootstrap', 'session_runtime', 'session_reset',
'periodic', 'visibility', 'retry_countdown', 'manual_retry', 'unspecified',
]);
const safeErrorNames = new Set([
'AbortError', 'TimeoutError', 'NetworkError', 'SecurityError', 'InvalidStateError',
'NotAllowedError', 'NotFoundError', 'TypeError', 'SyntaxError', 'RangeError', 'Error',
'HttpResponseNotOk',
]);
const operations = [];
const pendingOperations = new Map();
let operationsDropped = 0;
let nextOperationId = 0;
const events = [];
const counts = Object.create(null);
const first = Object.create(null);
const maxEvents = 256;
const round = (value) => Math.round(value * 10) / 10;
function mark(stage) {
try {
if (!allowed.has(stage)) return;
if (single.has(stage) && Object.hasOwn(first, stage)) return;
if (stage === 'session_restore_failed' && Object.hasOwn(first, 'session_restore_ok')) return;
const atMs = round(performance.now());
counts[stage] = (counts[stage] || 0) + 1;
if (!Object.hasOwn(first, stage)) first[stage] = atMs;
if (events.length < maxEvents) {
performance.mark('shine-stage0:' + stage);
events.push({ stage, atMs });
}
} catch {
// Измерение никогда не должно прерывать запуск приложения.
}
}
// Only fixed stage/operation names and fixed error classes can enter the export.
// Numeric ids are local measurement sequence numbers, never request/session ids.
function begin(operation, context = null) {
try {
if (!operationsAllowed.has(operation)) return null;
if (operations.length >= 256) { operationsDropped += 1; return null; }
const id = ++nextOperationId;
const item = { id, operation, startMs: round(performance.now()), endMs: null,
durationMs: null, outcome: 'pending' };
if (operationContexts.has(context)) item.context = context;
operations.push(item);
pendingOperations.set(id, item);
performance.mark('shine-stage0:' + operation + ':start');
return id;
} catch { return null; }
}
function finish(id, outcome = 'ok', error = null) {
try {
const item = pendingOperations.get(id);
if (!item) return;
pendingOperations.delete(id);
const endMs = round(performance.now());
item.endMs = endMs;
item.durationMs = round(endMs - item.startMs);
item.outcome = outcome === 'error' ? 'error'
: outcome === 'restore-unavailable' ? 'restore-unavailable'
: outcome === 'deduplicated' ? 'deduplicated' : 'ok';
if (item.outcome === 'error') {
let name;
try { name = error?.name; } catch {}
item.errorType = safeErrorNames.has(name) ? name : 'UnknownError';
}
performance.mark('shine-stage0:' + item.operation + ':end');
} catch {
// A diagnostic failure must never affect a network or UI operation.
}
}
function exportJson() {
const timing = Object.create(null);
for (const stage of allowed) {
if (Object.hasOwn(first, stage)) timing[stage] = first[stage];
}
const interval = (a, b) => a in first && b in first ? round(first[b] - first[a]) : null;
let domContentLoadedMs = null;
let firstContentfulPaintMs = null;
try {
const navigation = performance.getEntriesByType('navigation')[0];
if (navigation && Number.isFinite(navigation.domContentLoadedEventEnd)) {
domContentLoadedMs = round(navigation.domContentLoadedEventEnd);
}
const paint = performance.getEntriesByType('paint').find((item) => item.name === 'first-contentful-paint');
if (paint) firstContentfulPaintMs = round(paint.startTime);
} catch {}
return JSON.stringify({
schema: 'shine-stage0-v1',
units: 'milliseconds_since_navigation_start',
timing,
durations: {
cssAllSettledMs: interval('css_start', 'css_complete'),
cssRevealMs: interval('css_start', 'css_revealed'),
moduleLoadAndEvaluationMs: interval('main_js_requested', 'main_js_start'),
sessionRestoreMs: interval('session_restore_start',
'session_restore_ok' in first ? 'session_restore_ok' : 'session_restore_failed'),
splashRemovalMs: interval('bootstrap', 'splash_removed'),
renderToSplashLeaveMs: interval('first_dom_render', 'splash_leave'),
connectedToSplashLeaveMs: interval('status_connected', 'splash_leave'),
splashTransitionToRemovalMs: interval('splash_transition_start', 'splash_removed'),
},
browser: { domContentLoadedMs, firstContentfulPaintMs },
counters: {
cssLoaded: counts.css_ok || 0,
cssFailed: counts.css_error || 0,
wsAttempts: counts.ws_attempt || 0,
wsAttemptsAfterFirst: Math.max(0, (counts.ws_attempt || 0) - 1),
wsOpened: counts.ws_open || 0,
wsOpenErrors: counts.ws_error || 0,
wsClosed: counts.ws_close || 0,
sessionRestoreFailures: counts.session_restore_failed || 0,
reconnectRestoreFailures: counts.reconnect_restore_failed || 0,
eventsDropped: Object.values(counts).reduce((sum, n) => sum + n, 0) - events.length,
pingStarted: operations.filter((op) => op.operation === 'ping').length,
pingCompleted: operations.filter((op) => op.operation === 'ping' && op.endMs !== null).length,
connectedAssignments: counts.status_connected || 0,
splashFinishCalls: counts.splash_finish_called || 0,
operationsDropped,
},
events: events.slice(),
splashTrace: {
// No record means the operation was never observed. A pending record has
// endMs/durationMs null; it must not be confused with a zero-duration call.
operations: operations.map((item) => ({ ...item })),
},
}, null, 2);
}
Object.defineProperty(window, '__SHINE_STAGE0__', {
value: Object.freeze({ mark, begin, finish }), configurable: false, writable: false,
});
Object.defineProperty(window, '__SHINE_STAGE0_EXPORT__', {
value: exportJson, configurable: false, writable: false,
});
mark('bootstrap');
document.addEventListener('DOMContentLoaded', () => mark('dom_ready'), { once: true });
}());
</script>
<script>
(function applySavedThemeBeforePaint() {
let mode = 'system';
@@ -50,8 +219,13 @@ window.__SHINE_BUILD_HASH__ = '20261015230000';
// на долю секунды виден экран без CSS (логотип 640×640), а потом он «прыгает» на место.
const root = document.documentElement;
let pending = cssFiles.length;
const reveal = () => root.classList.add('shine-styles-ready');
const settle = () => { pending -= 1; if (pending <= 0) reveal(); };
const reveal = () => { root.classList.add('shine-styles-ready'); window.__SHINE_STAGE0__?.mark('css_revealed'); };
const settle = (event) => {
window.__SHINE_STAGE0__?.mark(event?.type === 'error' ? 'css_error' : 'css_ok');
pending -= 1;
if (pending <= 0) { window.__SHINE_STAGE0__?.mark('css_complete'); reveal(); }
};
window.__SHINE_STAGE0__?.mark('css_start');
cssFiles.forEach((file) => {
const link = document.createElement('link');
link.rel = 'stylesheet';
@@ -484,6 +658,7 @@ window.__SHINE_BUILD_HASH__ = '20261015230000';
const script = document.createElement('script');
script.type = 'module';
script.src = isLocalPreview ? `./js/app.js?v=${v}&local=${Date.now()}` : `./js/app.js?v=${v}`;
window.__SHINE_STAGE0__?.mark('main_js_requested');
document.body.appendChild(script);
}());
</script>