SHA256
Доработать диагностику запуска UI
This commit is contained in:
+131
-21
@@ -129,6 +129,8 @@ import * as addPersonalPublicChatView from './pages/add-personal-public-chat-vie
|
||||
import * as networkView from './pages/network-version-switcher.js?v=202610170100';
|
||||
import * as notificationsView from './pages/notifications-view.js?v=202610130400';
|
||||
|
||||
window.__SHINE_STAGE0__?.mark('main_js_start');
|
||||
|
||||
const CONVERSATION_CLEAR_NOTICE_TEXT = 'История переписки очищена с этого места';
|
||||
const DM_UNSUPPORTED_FORMAT_TEXT = 'Формат сообщения не поддерживается';
|
||||
const DM_DECRYPT_FAILED_TEXT = 'Не удалось расшифровать сообщение';
|
||||
@@ -221,6 +223,7 @@ const UI_BUILD_HASH_PATTERN = /window\.__SHINE_BUILD_HASH__\s*=\s*'([^']+)'/;
|
||||
|
||||
let currentCleanup = null;
|
||||
let pingIntervalId = null;
|
||||
let connectionMonitorStartSource = '';
|
||||
let reconnectIntervalId = null;
|
||||
let channelsPrefetchTimerId = null;
|
||||
let channelsPrefetchEpoch = 0;
|
||||
@@ -836,6 +839,7 @@ function refreshConnectionUi() {
|
||||
}
|
||||
|
||||
function finishInitialConnectionSplash() {
|
||||
window.__SHINE_STAGE0__?.mark('splash_finish_called');
|
||||
if (initialConnectionCompleted) return;
|
||||
initialConnectionCompleted = true;
|
||||
if (!initialSplashEl) {
|
||||
@@ -843,8 +847,27 @@ function finishInitialConnectionSplash() {
|
||||
return;
|
||||
}
|
||||
|
||||
// The CSS 'is-leaving' mutation is not the actual transition start.
|
||||
// This debug-only passive listener observes the browser's transitionstart event.
|
||||
if (window.__SHINE_STAGE0__) {
|
||||
initialSplashEl.addEventListener('transitionstart', (event) => {
|
||||
if (event.target === initialSplashEl && event.propertyName === 'opacity') {
|
||||
window.__SHINE_STAGE0__?.mark('splash_transition_start');
|
||||
}
|
||||
}, { passive: true });
|
||||
}
|
||||
initialSplashEl.classList.add('is-leaving');
|
||||
const removeSplash = () => initialSplashEl.remove();
|
||||
window.__SHINE_STAGE0__?.mark('splash_leave');
|
||||
let splashRemovalRecorded = false;
|
||||
const removeSplash = (event) => {
|
||||
initialSplashEl.remove();
|
||||
window.__SHINE_STAGE0__?.mark('splash_removed');
|
||||
if (!splashRemovalRecorded) {
|
||||
splashRemovalRecorded = true;
|
||||
window.__SHINE_STAGE0__?.mark(event?.type === 'transitionend'
|
||||
? 'splash_removed_via_transition' : 'splash_removed_via_timeout');
|
||||
}
|
||||
};
|
||||
initialSplashEl.addEventListener('transitionend', removeSplash, { once: true });
|
||||
window.setTimeout(removeSplash, 700);
|
||||
refreshConnectionUi();
|
||||
@@ -858,7 +881,7 @@ function startConnectionCountdown() {
|
||||
if (secs <= 0 && !connectionCheckInFlight) {
|
||||
connectionStatusText = '';
|
||||
setConnectionStatus('connecting', 'Соединяюсь…');
|
||||
void checkConnectionHealth();
|
||||
void checkConnectionHealth('retry_countdown');
|
||||
return;
|
||||
}
|
||||
refreshConnectionUi();
|
||||
@@ -1028,6 +1051,7 @@ function setConnectionStatus(nextState, text = '') {
|
||||
const state = String(nextState || '').trim();
|
||||
if (!state) return;
|
||||
connectionState = state;
|
||||
if (state === 'connected') window.__SHINE_STAGE0__?.mark('status_connected');
|
||||
connectionStatusText = String(text || '').trim();
|
||||
if (state === 'connected') {
|
||||
finishInitialConnectionSplash();
|
||||
@@ -1047,7 +1071,7 @@ async function triggerImmediateConnectionRetry() {
|
||||
if (connectionCheckInFlight) return;
|
||||
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
||||
setConnectionStatus('connecting', 'Соединяюсь…');
|
||||
await checkConnectionHealth();
|
||||
await checkConnectionHealth('manual_retry');
|
||||
}
|
||||
|
||||
function extractBuildHashFromHtml(htmlText) {
|
||||
@@ -1058,14 +1082,21 @@ function extractBuildHashFromHtml(htmlText) {
|
||||
}
|
||||
|
||||
async function fetchCurrentHostUiBuildHash() {
|
||||
const traceId = window.__SHINE_STAGE0__?.begin?.('ui_version_fetch');
|
||||
try {
|
||||
const url = `./index.html?build_probe=${Date.now()}`;
|
||||
const response = await fetch(url, { cache: 'no-store' });
|
||||
if (!response?.ok) return '';
|
||||
if (!response?.ok) {
|
||||
window.__SHINE_STAGE0__?.finish?.(traceId, 'error', { name: 'HttpResponseNotOk' });
|
||||
return '';
|
||||
}
|
||||
const html = await response.text();
|
||||
return extractBuildHashFromHtml(html);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
window.__SHINE_STAGE0__?.finish?.(traceId, 'error', error);
|
||||
return '';
|
||||
} finally {
|
||||
window.__SHINE_STAGE0__?.finish?.(traceId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1075,6 +1106,8 @@ async function checkAndReloadIfUiUpdated(remoteHashRaw) {
|
||||
if (uiVersionCheckInFlight) return;
|
||||
|
||||
uiVersionCheckInFlight = true;
|
||||
const traceId = window.__SHINE_STAGE0__?.begin?.('ui_version_ping');
|
||||
let traceError = null;
|
||||
try {
|
||||
const latestHostHash = await fetchCurrentHostUiBuildHash();
|
||||
if (!latestHostHash || latestHostHash === CURRENT_BUILD_HASH) {
|
||||
@@ -1092,27 +1125,51 @@ async function checkAndReloadIfUiUpdated(remoteHashRaw) {
|
||||
delayMs: 600,
|
||||
activateWaitingWorker: true,
|
||||
});
|
||||
} catch (error) {
|
||||
traceError = error;
|
||||
throw error;
|
||||
} finally {
|
||||
window.__SHINE_STAGE0__?.finish?.(traceId, traceError ? 'error' : 'ok', traceError);
|
||||
uiVersionCheckInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function refreshServiceWorkers({ activateWaitingWorker = false } = {}) {
|
||||
if (!('serviceWorker' in navigator)) return;
|
||||
const trace = window.__SHINE_STAGE0__;
|
||||
const context = activateWaitingWorker ? 'reload' : 'first_ping';
|
||||
const refreshId = trace?.begin?.('sw_refresh', context);
|
||||
let listId = null;
|
||||
let refreshError = null;
|
||||
try {
|
||||
listId = trace?.begin?.('sw_get_registrations', context);
|
||||
const registrations = await navigator.serviceWorker.getRegistrations();
|
||||
trace?.finish?.(listId);
|
||||
listId = null;
|
||||
await Promise.all(registrations.map(async (registration) => {
|
||||
const updateId = trace?.begin?.('sw_registration_update', context);
|
||||
try {
|
||||
await registration.update();
|
||||
} catch {}
|
||||
trace?.finish?.(updateId);
|
||||
} catch (error) {
|
||||
trace?.finish?.(updateId, 'error', error);
|
||||
}
|
||||
if (activateWaitingWorker && registration.waiting) {
|
||||
const waitingId = trace?.begin?.('sw_skip_waiting', context);
|
||||
try {
|
||||
registration.waiting.postMessage({ type: 'SKIP_WAITING' });
|
||||
} catch {}
|
||||
trace?.finish?.(waitingId);
|
||||
} catch (error) {
|
||||
trace?.finish?.(waitingId, 'error', error);
|
||||
}
|
||||
}
|
||||
}));
|
||||
} catch {
|
||||
} catch (error) {
|
||||
refreshError = error;
|
||||
trace?.finish?.(listId, 'error', error);
|
||||
// ignore service worker update failures
|
||||
} finally {
|
||||
trace?.finish?.(refreshId, refreshError ? 'error' : 'ok', refreshError);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1141,12 +1198,21 @@ function scheduleUiReload({
|
||||
async function tryUpdatePwaOnFirstConnectedPing() {
|
||||
if (pwaUpdateCheckAttempted) return;
|
||||
pwaUpdateCheckAttempted = true;
|
||||
await refreshServiceWorkers({ activateWaitingWorker: false });
|
||||
const traceId = window.__SHINE_STAGE0__?.begin?.('pwa_first_ping_update');
|
||||
try {
|
||||
await refreshServiceWorkers({ activateWaitingWorker: false });
|
||||
} catch (error) {
|
||||
window.__SHINE_STAGE0__?.finish?.(traceId, 'error', error);
|
||||
throw error;
|
||||
} finally {
|
||||
window.__SHINE_STAGE0__?.finish?.(traceId);
|
||||
}
|
||||
}
|
||||
|
||||
async function runPeriodicUiVersionCheck() {
|
||||
if (uiUpdateReloadScheduled) return;
|
||||
if (uiVersionCheckInFlight) return;
|
||||
const traceId = window.__SHINE_STAGE0__?.begin?.('ui_version_periodic');
|
||||
try {
|
||||
const latestHostHash = await fetchCurrentHostUiBuildHash();
|
||||
if (!latestHostHash || !CURRENT_BUILD_HASH || latestHostHash === CURRENT_BUILD_HASH) return;
|
||||
@@ -1156,8 +1222,11 @@ async function runPeriodicUiVersionCheck() {
|
||||
delayMs: 600,
|
||||
activateWaitingWorker: true,
|
||||
});
|
||||
} catch {
|
||||
} catch (error) {
|
||||
window.__SHINE_STAGE0__?.finish?.(traceId, 'error', error);
|
||||
// ignore periodic check errors
|
||||
} finally {
|
||||
window.__SHINE_STAGE0__?.finish?.(traceId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1170,13 +1239,23 @@ function startPeriodicUiVersionCheck() {
|
||||
}, UI_VERSION_PERIODIC_CHECK_MS);
|
||||
}
|
||||
|
||||
async function checkConnectionHealth() {
|
||||
async function checkConnectionHealth(source = 'unspecified') {
|
||||
window.__SHINE_STAGE0__?.mark('health_invoked');
|
||||
if (state.session.isLocalDemo) {
|
||||
window.__SHINE_STAGE0__?.mark('health_local_demo');
|
||||
const demoId = window.__SHINE_STAGE0__?.begin?.('connection_health');
|
||||
setConnectionStatus('connected');
|
||||
window.__SHINE_STAGE0__?.finish?.(demoId);
|
||||
return;
|
||||
}
|
||||
if (connectionCheckInFlight) {
|
||||
window.__SHINE_STAGE0__?.mark('health_skipped_inflight');
|
||||
return;
|
||||
}
|
||||
if (connectionCheckInFlight) return;
|
||||
connectionCheckInFlight = true;
|
||||
const trace = window.__SHINE_STAGE0__;
|
||||
const healthId = trace?.begin?.('connection_health', source);
|
||||
let pingId = null;
|
||||
if (connectionState !== 'connected') {
|
||||
setConnectionStatus('connecting');
|
||||
}
|
||||
@@ -1188,25 +1267,47 @@ async function checkConnectionHealth() {
|
||||
if (!restored) {
|
||||
connectionStatusText = '';
|
||||
setConnectionStatus('disconnected');
|
||||
trace?.finish?.(healthId, 'restore-unavailable');
|
||||
return;
|
||||
}
|
||||
}
|
||||
pingId = trace?.begin?.('ping');
|
||||
const pingResp = await authService.ws.request('Ping', { ts: Date.now() }, 7000);
|
||||
trace?.finish?.(pingId);
|
||||
pingId = null;
|
||||
const remoteUiBuildHash = pingResp?.payload?.uiBuildHash || pingResp?.uiBuildHash || '';
|
||||
void checkAndReloadIfUiUpdated(remoteUiBuildHash);
|
||||
await tryUpdatePwaOnFirstConnectedPing();
|
||||
// Проверка SW остаётся одноразовой, но не задерживает статус после успешного Ping.
|
||||
void tryUpdatePwaOnFirstConnectedPing().catch(() => {
|
||||
// Ошибка уже отмечена диагностикой Stage 0.1; соединение определяет только Ping.
|
||||
});
|
||||
setConnectionStatus('connected');
|
||||
} catch {
|
||||
} catch (error) {
|
||||
trace?.finish?.(pingId, 'error', error);
|
||||
trace?.finish?.(healthId, 'error', error);
|
||||
connectionStatusText = '';
|
||||
setConnectionStatus('disconnected');
|
||||
} finally {
|
||||
trace?.finish?.(healthId);
|
||||
connectionCheckInFlight = false;
|
||||
}
|
||||
}
|
||||
|
||||
function startConnectionMonitor() {
|
||||
function startConnectionMonitor(source = 'unspecified') {
|
||||
const trace = window.__SHINE_STAGE0__;
|
||||
const monitorId = trace?.begin?.('monitor_start', source);
|
||||
if (state.session.isLocalDemo) {
|
||||
setConnectionStatus('connected');
|
||||
trace?.finish?.(monitorId);
|
||||
return;
|
||||
}
|
||||
// При первой загрузке bootstrap и session_runtime могут оба запустить монитор.
|
||||
// После успешного Ping второй старт не нужен. Сброс сессии и все прочие
|
||||
// независимые проверки по-прежнему запускаются без подавления.
|
||||
const sameInitialStartup = (source === 'bootstrap' && connectionMonitorStartSource === 'session_runtime')
|
||||
|| (source === 'session_runtime' && connectionMonitorStartSource === 'bootstrap');
|
||||
if (sameInitialStartup && pingIntervalId && (connectionState === 'connected' || connectionCheckInFlight)) {
|
||||
trace?.finish?.(monitorId, 'deduplicated');
|
||||
return;
|
||||
}
|
||||
if (pingIntervalId) {
|
||||
@@ -1214,16 +1315,18 @@ function startConnectionMonitor() {
|
||||
pingIntervalId = null;
|
||||
}
|
||||
|
||||
connectionMonitorStartSource = source;
|
||||
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
||||
void checkConnectionHealth();
|
||||
void checkConnectionHealth(source);
|
||||
|
||||
pingIntervalId = window.setInterval(() => {
|
||||
connectionNextRetryAtMs = Date.now() + CONNECTION_CHECK_INTERVAL_MS;
|
||||
if (connectionState === 'disconnected') {
|
||||
refreshConnectionUi();
|
||||
}
|
||||
void checkConnectionHealth();
|
||||
void checkConnectionHealth('periodic');
|
||||
}, CONNECTION_CHECK_INTERVAL_MS);
|
||||
trace?.finish?.(monitorId);
|
||||
}
|
||||
|
||||
function isReconnectAllowedNow() {
|
||||
@@ -1277,6 +1380,7 @@ function resolveSignedDmChatId({ parsed, login }) {
|
||||
async function ensureSessionAfterWsReconnect() {
|
||||
if (!state.session.isAuthorized) return true;
|
||||
if (wsSessionRestoreInFlight) return wsSessionRestoreInFlight;
|
||||
window.__SHINE_STAGE0__?.mark('reconnect_restore_start');
|
||||
|
||||
wsSessionRestoreInFlight = (async () => {
|
||||
try {
|
||||
@@ -1291,8 +1395,10 @@ async function ensureSessionAfterWsReconnect() {
|
||||
source: 'ws-reconnect',
|
||||
message: 'Сессия восстановлена после переподключения WS',
|
||||
});
|
||||
window.__SHINE_STAGE0__?.mark('reconnect_restore_ok');
|
||||
return true;
|
||||
} catch (error) {
|
||||
window.__SHINE_STAGE0__?.mark('reconnect_restore_failed');
|
||||
if (isSessionInvalidError(error)) {
|
||||
await terminateCurrentSession({
|
||||
infoMessage: 'Ваша сессия устарела. Авторизируйтесь заново.',
|
||||
@@ -1534,6 +1640,7 @@ function renderApp() {
|
||||
}
|
||||
|
||||
screenEl.append(screen);
|
||||
window.__SHINE_STAGE0__?.mark('first_dom_render');
|
||||
const pageCleanup = typeof screen.cleanup === 'function' ? screen.cleanup : null;
|
||||
const scrollToBottomControl = attachPageScrollToBottom(pageId, screen);
|
||||
currentCleanup = () => {
|
||||
@@ -1575,16 +1682,19 @@ function refreshUnreadUi() {
|
||||
async function tryAutoLogin() {
|
||||
if (state.session.isLocalDemo) return;
|
||||
if (!state.session.login || !state.session.sessionId) return;
|
||||
window.__SHINE_STAGE0__?.mark('session_restore_start');
|
||||
try {
|
||||
await authService.reconnect(state.entrySettings.shineServer);
|
||||
const resumed = await authService.resumeSession(state.session.login, state.session.sessionId);
|
||||
authorizeSession(resumed);
|
||||
window.__SHINE_STAGE0__?.mark('session_restore_ok');
|
||||
await refreshSessions();
|
||||
try {
|
||||
const contacts = await authService.listContacts();
|
||||
setContacts(contacts.contacts || []);
|
||||
} catch {}
|
||||
} catch (error) {
|
||||
window.__SHINE_STAGE0__?.mark('session_restore_failed');
|
||||
if (isSessionInvalidError(error)) {
|
||||
const result = await closeSavedProfile(state.session.login);
|
||||
if (result?.nextProfile) {
|
||||
@@ -1610,7 +1720,7 @@ async function ensureSessionRuntimeStarted() {
|
||||
});
|
||||
}
|
||||
|
||||
startConnectionMonitor();
|
||||
startConnectionMonitor('session_runtime');
|
||||
startChannelsPrefetch();
|
||||
|
||||
if (reconnectIntervalId) {
|
||||
@@ -1664,7 +1774,7 @@ async function init() {
|
||||
setSessionResetHandler(() => {
|
||||
sessionRuntimeStarted = false;
|
||||
stopChannelsPrefetch();
|
||||
startConnectionMonitor();
|
||||
startConnectionMonitor('session_reset');
|
||||
clearKeepAliveEntries();
|
||||
if (reconnectIntervalId) {
|
||||
window.clearInterval(reconnectIntervalId);
|
||||
@@ -2068,7 +2178,7 @@ async function init() {
|
||||
}
|
||||
await hydrateMessagesFromStore();
|
||||
if (!state.session.isLocalDemo) {
|
||||
startConnectionMonitor();
|
||||
startConnectionMonitor('bootstrap');
|
||||
startPeriodicUiVersionCheck();
|
||||
}
|
||||
await ensureSessionRuntimeStarted();
|
||||
@@ -2090,7 +2200,7 @@ async function init() {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState !== 'visible') return;
|
||||
void tryLockPortraitOrientation();
|
||||
void checkConnectionHealth();
|
||||
void checkConnectionHealth('visibility');
|
||||
});
|
||||
window.addEventListener('orientationchange', () => {
|
||||
void tryLockPortraitOrientation();
|
||||
|
||||
Reference in New Issue
Block a user