fix and update

This commit is contained in:
lendry
2026-06-30 08:58:36 +03:00
parent 40057b64c8
commit f1d6a5167f
4 changed files with 85 additions and 69 deletions

View File

@@ -56,7 +56,7 @@ function OAuthAuthorizeContent() {
const clientLabel = clientName ?? consentInfo?.client?.name ?? 'Приложение'; const clientLabel = clientName ?? consentInfo?.client?.name ?? 'Приложение';
useEffect(() => { useEffect(() => {
if (!clientId) return; if (!clientId || isLoading) return;
let cancelled = false; let cancelled = false;
void fetchOAuthClientPublicInfo(clientId) void fetchOAuthClientPublicInfo(clientId)
.then((info) => { .then((info) => {
@@ -68,7 +68,7 @@ function OAuthAuthorizeContent() {
return () => { return () => {
cancelled = true; cancelled = true;
}; };
}, [clientId]); }, [clientId, isLoading]);
useEffect(() => { useEffect(() => {
if (!searchParams.has('userId')) return; if (!searchParams.has('userId')) return;

View File

@@ -16,17 +16,15 @@ import {
buildAuthDevicePayload, buildAuthDevicePayload,
IdentifyResponse, IdentifyResponse,
getApiErrorMessage, getApiErrorMessage,
isApiGatewayReady,
isPinRequiredError, isPinRequiredError,
OtpSendResponse, OtpSendResponse,
PasswordlessAuthResponse, PasswordlessAuthResponse,
PinVerificationResponse, PinVerificationResponse,
PublicUser, PublicUser,
refreshAuthSession, refreshAuthSession,
resetApiGatewayWarmup,
resetPinRequiredNotification, resetPinRequiredNotification,
scheduleFedcmSessionSync,
setPinRequiredHandler, setPinRequiredHandler,
syncFedcmSession
} from '@/lib/api'; } from '@/lib/api';
import { useToast } from './toast-provider'; import { useToast } from './toast-provider';
import { PinLockModal } from './pin-lock-modal'; import { PinLockModal } from './pin-lock-modal';
@@ -94,9 +92,7 @@ function applySessionState(
setters.activatePinLock(session.sessionId ?? ''); setters.activatePinLock(session.sessionId ?? '');
} else { } else {
setters.clearPinLock(); setters.clearPinLock();
void ensureApiGatewayReady().then(() => { scheduleFedcmSessionSync();
void syncFedcmSession();
});
} }
} }
@@ -163,16 +159,11 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
cacheUserProfile(auth.user); cacheUserProfile(auth.user);
setHasStoredSession(true); setHasStoredSession(true);
clearPinLock(); clearPinLock();
initialBootstrapDoneRef.current = false;
resetApiGatewayWarmup();
setIsLoading(true);
void ensureApiGatewayReady().finally(() => {
initialBootstrapDoneRef.current = true; initialBootstrapDoneRef.current = true;
setIsLoading(false); setIsLoading(false);
if (auth.pinVerified !== false) { if (auth.pinVerified !== false) {
void syncFedcmSession(auth.accessToken); scheduleFedcmSessionSync(auth.accessToken, 2000);
} }
});
}, },
[clearPinLock] [clearPinLock]
); );
@@ -182,7 +173,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
window.localStorage.removeItem(AUTH_REFRESH_KEY); window.localStorage.removeItem(AUTH_REFRESH_KEY);
window.localStorage.removeItem(AUTH_SESSION_KEY); window.localStorage.removeItem(AUTH_SESSION_KEY);
window.localStorage.removeItem(AUTH_USER_CACHE_KEY); window.localStorage.removeItem(AUTH_USER_CACHE_KEY);
resetApiGatewayWarmup();
initialBootstrapDoneRef.current = false; initialBootstrapDoneRef.current = false;
setToken(null); setToken(null);
setUser(null); setUser(null);
@@ -210,7 +200,7 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
const isInitialBootstrap = !initialBootstrapDoneRef.current; const isInitialBootstrap = !initialBootstrapDoneRef.current;
if (isInitialBootstrap) { if (isInitialBootstrap) {
setIsLoading(true); setIsLoading(true);
resetApiGatewayWarmup(); await ensureApiGatewayReady();
} }
try { try {
@@ -273,17 +263,6 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
if (message) showToast(message); if (message) showToast(message);
logout(); logout();
} finally { } finally {
const hasSession = Boolean(
window.localStorage.getItem(AUTH_TOKEN_KEY) || window.localStorage.getItem(AUTH_REFRESH_KEY)
);
if (hasSession && isInitialBootstrap) {
const bootstrapDeadline = Date.now() + 120_000;
while (!isApiGatewayReady() && Date.now() < bootstrapDeadline) {
await ensureApiGatewayReady(true);
if (isApiGatewayReady()) break;
await new Promise((resolve) => setTimeout(resolve, 800));
}
}
if (isInitialBootstrap) { if (isInitialBootstrap) {
initialBootstrapDoneRef.current = true; initialBootstrapDoneRef.current = true;
setIsLoading(false); setIsLoading(false);

View File

@@ -544,6 +544,9 @@ export async function refreshAuthSession(): Promise<RefreshSessionResponse> {
export async function syncFedcmSession(accessToken?: string | null) { export async function syncFedcmSession(accessToken?: string | null) {
const token = resolveAccessToken(accessToken); const token = resolveAccessToken(accessToken);
if (typeof window === 'undefined' || !token) return; if (typeof window === 'undefined' || !token) return;
if (!isApiGatewayReady()) {
await ensureApiGatewayReady();
}
try { try {
await apiFetch<{ synced: boolean }>( await apiFetch<{ synced: boolean }>(
'/fedcm/session/sync', '/fedcm/session/sync',
@@ -558,6 +561,25 @@ export async function syncFedcmSession(accessToken?: string | null) {
} }
} }
let fedcmSyncTimer: ReturnType<typeof setTimeout> | null = null;
let fedcmSyncInFlight = false;
/** Откладывает FedCM sync после OAuth/bootstrap, чтобы не конкурировать с consent/session. */
export function scheduleFedcmSessionSync(accessToken?: string | null, delayMs = 1500) {
if (typeof window === 'undefined') return;
if (fedcmSyncTimer) {
clearTimeout(fedcmSyncTimer);
}
fedcmSyncTimer = setTimeout(() => {
fedcmSyncTimer = null;
if (fedcmSyncInFlight) return;
fedcmSyncInFlight = true;
void syncFedcmSession(accessToken).finally(() => {
fedcmSyncInFlight = false;
});
}, delayMs);
}
async function trySilentTokenRefresh(): Promise<RefreshSessionResponse | null> { async function trySilentTokenRefresh(): Promise<RefreshSessionResponse | null> {
try { try {
const refreshed = await refreshAuthSession(); const refreshed = await refreshAuthSession();
@@ -654,11 +676,12 @@ export function buildSystemSettingPayload(setting: Pick<SystemSetting, 'key' | '
} }
const GATEWAY_RETRY_STATUS = new Set([502, 503, 504]); const GATEWAY_RETRY_STATUS = new Set([502, 503, 504]);
const GATEWAY_RETRY_ATTEMPTS = 8; const GATEWAY_RETRY_ATTEMPTS = 6;
const GATEWAY_WARMUP_MAX_ATTEMPTS = 80; const GATEWAY_WARMUP_INITIAL_DELAY_MS = 500;
const GATEWAY_WARMUP_DELAY_MS = 400; const GATEWAY_WARMUP_DELAY_MS = 450;
const GATEWAY_READY_CONSECUTIVE_OK = 2; const GATEWAY_READY_CONSECUTIVE_OK = 1;
const GATEWAY_WARMUP_MAX_DELAY_MS = 2500; const GATEWAY_WARMUP_MAX_DELAY_MS = 2200;
const GATEWAY_WARMUP_MAX_TOTAL_MS = 90_000;
function sleep(ms: number): Promise<void> { function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms)); return new Promise((resolve) => setTimeout(resolve, ms));
@@ -674,7 +697,6 @@ export function resetApiGatewayWarmup() {
export function invalidateApiGatewayReady() { export function invalidateApiGatewayReady() {
gatewayReadyResolved = false; gatewayReadyResolved = false;
gatewayReadyPromise = null;
} }
export function isApiGatewayReady() { export function isApiGatewayReady() {
@@ -685,11 +707,13 @@ export function markApiGatewayReady() {
gatewayReadyResolved = true; gatewayReadyResolved = true;
} }
async function probeGatewayReady(): Promise<boolean> { /** Liveness: nginx → api-gateway HTTP. Не /health/ready — gRPC 503 не должен блокировать SPA и засорять консоль. */
async function probeGatewayAlive(): Promise<boolean> {
try { try {
const response = await fetch(`${getApiUrl()}/health/ready`, { const response = await fetch(`${getApiUrl()}/health`, {
method: 'GET', method: 'GET',
cache: 'no-store' cache: 'no-store',
signal: AbortSignal.timeout(4500)
}); });
return response.ok; return response.ok;
} catch { } catch {
@@ -697,20 +721,14 @@ async function probeGatewayReady(): Promise<boolean> {
} }
} }
/** Ждёт готовности api-gateway и sso-core (readiness по gRPC, не liveness /health). */ async function waitForGatewayAlive(): Promise<void> {
export async function ensureApiGatewayReady(force = false): Promise<void> { await sleep(GATEWAY_WARMUP_INITIAL_DELAY_MS);
if (typeof window === 'undefined') return; const deadline = Date.now() + GATEWAY_WARMUP_MAX_TOTAL_MS;
if (gatewayReadyResolved && !force) return;
if (gatewayReadyPromise && !force) return gatewayReadyPromise;
if (force) {
gatewayReadyResolved = false;
gatewayReadyPromise = null;
}
gatewayReadyPromise = (async () => {
await sleep(600);
let consecutiveOk = 0; let consecutiveOk = 0;
for (let attempt = 0; attempt < GATEWAY_WARMUP_MAX_ATTEMPTS; attempt++) { let attempt = 0;
if (await probeGatewayReady()) {
while (Date.now() < deadline) {
if (await probeGatewayAlive()) {
consecutiveOk += 1; consecutiveOk += 1;
if (consecutiveOk >= GATEWAY_READY_CONSECUTIVE_OK) { if (consecutiveOk >= GATEWAY_READY_CONSECUTIVE_OK) {
gatewayReadyResolved = true; gatewayReadyResolved = true;
@@ -719,34 +737,53 @@ export async function ensureApiGatewayReady(force = false): Promise<void> {
} else { } else {
consecutiveOk = 0; consecutiveOk = 0;
} }
const delay = Math.min(GATEWAY_WARMUP_DELAY_MS * 1.35 ** attempt, GATEWAY_WARMUP_MAX_DELAY_MS); attempt += 1;
const delay = Math.min(GATEWAY_WARMUP_DELAY_MS * 1.28 ** attempt, GATEWAY_WARMUP_MAX_DELAY_MS);
await sleep(delay); await sleep(delay);
} }
gatewayReadyResolved = true;
}
/** Один общий прогрев перед API: без сброса promise и без десятков параллельных проб /health/ready. */
export async function ensureApiGatewayReady(force = false): Promise<void> {
if (typeof window === 'undefined') return;
if (gatewayReadyResolved && !force) return;
if (gatewayReadyPromise) return gatewayReadyPromise;
if (force) {
gatewayReadyResolved = false;
}
gatewayReadyPromise = waitForGatewayAlive().finally(() => {
gatewayReadyPromise = null; gatewayReadyPromise = null;
})(); });
return gatewayReadyPromise; return gatewayReadyPromise;
} }
function gatewayRetryDelay(attempt: number): number {
return Math.min(500 * (attempt + 1), 2800);
}
/** Повтор при кратковременном 502/503/504 (nginx не достучался до api-gateway после перезапуска). */ /** Повтор при кратковременном 502/503/504 (nginx не достучался до api-gateway после перезапуска). */
async function fetchWithGatewayRetry(url: string, init: RequestInit): Promise<Response> { async function fetchWithGatewayRetry(url: string, init: RequestInit): Promise<Response> {
let lastNetworkError: unknown; let lastNetworkError: unknown;
for (let attempt = 0; attempt < GATEWAY_RETRY_ATTEMPTS; attempt++) { for (let attempt = 0; attempt < GATEWAY_RETRY_ATTEMPTS; attempt++) {
try { try {
const response = await fetch(url, init); const response = await fetch(url, init);
if (response.ok) {
markApiGatewayReady();
}
if (GATEWAY_RETRY_STATUS.has(response.status) && attempt + 1 < GATEWAY_RETRY_ATTEMPTS) { if (GATEWAY_RETRY_STATUS.has(response.status) && attempt + 1 < GATEWAY_RETRY_ATTEMPTS) {
invalidateApiGatewayReady(); await sleep(gatewayRetryDelay(attempt));
await ensureApiGatewayReady(true);
await sleep(400 * (attempt + 1));
continue; continue;
} }
return response; return response;
} catch (error) { } catch (error) {
lastNetworkError = error; lastNetworkError = error;
if (attempt + 1 < GATEWAY_RETRY_ATTEMPTS) { if (attempt + 1 < GATEWAY_RETRY_ATTEMPTS) {
invalidateApiGatewayReady(); await sleep(gatewayRetryDelay(attempt));
await ensureApiGatewayReady(true);
await sleep(400 * (attempt + 1));
continue; continue;
} }
throw mapFetchError(error); throw mapFetchError(error);
@@ -804,13 +841,14 @@ export async function apiFetch<T>(path: string, options: RequestInit = {}, token
if (allowRetry && isGatewayUnavailableError(error)) { if (allowRetry && isGatewayUnavailableError(error)) {
invalidateApiGatewayReady(); invalidateApiGatewayReady();
await ensureApiGatewayReady(true); await sleep(900);
return apiFetch<T>(path, options, token, false); return apiFetch<T>(path, options, token, false);
} }
throw error; throw error;
} }
markApiGatewayReady();
return response.json() as Promise<T>; return response.json() as Promise<T>;
} }

View File

@@ -1,4 +1,4 @@
import { ensureApiGatewayReady, invalidateApiGatewayReady } from '@/lib/api'; import { ensureApiGatewayReady } from '@/lib/api';
const GATEWAY_RETRY_STATUS = new Set([502, 503, 504]); const GATEWAY_RETRY_STATUS = new Set([502, 503, 504]);
const MEDIA_FETCH_MAX_ATTEMPTS = 8; const MEDIA_FETCH_MAX_ATTEMPTS = 8;
@@ -32,7 +32,6 @@ export async function fetchMediaBlobWithRetry(
}); });
if (GATEWAY_RETRY_STATUS.has(response.status) && attempt + 1 < MEDIA_FETCH_MAX_ATTEMPTS) { if (GATEWAY_RETRY_STATUS.has(response.status) && attempt + 1 < MEDIA_FETCH_MAX_ATTEMPTS) {
invalidateApiGatewayReady();
await sleep(350 * (attempt + 1)); await sleep(350 * (attempt + 1));
continue; continue;
} }