fix and update
This commit is contained in:
@@ -677,9 +677,11 @@ export function buildSystemSettingPayload(setting: Pick<SystemSetting, 'key' | '
|
||||
}
|
||||
|
||||
const GATEWAY_RETRY_STATUS = new Set([502, 503, 504]);
|
||||
const GATEWAY_RETRY_ATTEMPTS = 2;
|
||||
const GATEWAY_PROBE_MAX_ATTEMPTS = 4;
|
||||
const GATEWAY_PROBE_DELAY_MS = 600;
|
||||
const GATEWAY_RETRY_ATTEMPTS = 4;
|
||||
const GATEWAY_PROBE_MAX_ATTEMPTS = 48;
|
||||
const GATEWAY_PROBE_BASE_DELAY_MS = 450;
|
||||
const API_MAX_CONCURRENT = 8;
|
||||
const API_READY_EVENT = 'idp-api-ready';
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, ms));
|
||||
@@ -687,6 +689,8 @@ function sleep(ms: number): Promise<void> {
|
||||
|
||||
let gatewayReadyResolved = false;
|
||||
let gatewayReadyPromise: Promise<void> | null = null;
|
||||
let activeApiRequests = 0;
|
||||
const apiRequestWaiters: Array<() => void> = [];
|
||||
|
||||
export function resetApiGatewayWarmup() {
|
||||
gatewayReadyResolved = false;
|
||||
@@ -702,10 +706,41 @@ export function isApiGatewayReady() {
|
||||
}
|
||||
|
||||
export function markApiGatewayReady() {
|
||||
if (gatewayReadyResolved) return;
|
||||
gatewayReadyResolved = true;
|
||||
if (typeof window !== 'undefined') {
|
||||
window.dispatchEvent(new CustomEvent(API_READY_EVENT));
|
||||
}
|
||||
}
|
||||
|
||||
/** Liveness: nginx → api-gateway HTTP. Не /health/ready — gRPC 503 не должен блокировать SPA и засорять консоль. */
|
||||
export function subscribeApiReady(listener: () => void): () => void {
|
||||
if (typeof window === 'undefined') return () => undefined;
|
||||
if (gatewayReadyResolved) {
|
||||
listener();
|
||||
return () => undefined;
|
||||
}
|
||||
window.addEventListener(API_READY_EVENT, listener);
|
||||
return () => window.removeEventListener(API_READY_EVENT, listener);
|
||||
}
|
||||
|
||||
async function acquireApiSlot(): Promise<void> {
|
||||
if (activeApiRequests < API_MAX_CONCURRENT) {
|
||||
activeApiRequests += 1;
|
||||
return;
|
||||
}
|
||||
await new Promise<void>((resolve) => {
|
||||
apiRequestWaiters.push(resolve);
|
||||
});
|
||||
activeApiRequests += 1;
|
||||
}
|
||||
|
||||
function releaseApiSlot(): void {
|
||||
activeApiRequests = Math.max(0, activeApiRequests - 1);
|
||||
const next = apiRequestWaiters.shift();
|
||||
if (next) next();
|
||||
}
|
||||
|
||||
/** Liveness: nginx → api-gateway HTTP. */
|
||||
async function probeGatewayAlive(): Promise<boolean> {
|
||||
try {
|
||||
const response = await fetch(`${getApiUrl()}/health`, {
|
||||
@@ -720,18 +755,22 @@ async function probeGatewayAlive(): Promise<boolean> {
|
||||
}
|
||||
|
||||
async function waitForGatewayAlive(): Promise<void> {
|
||||
if (gatewayReadyResolved) return;
|
||||
|
||||
for (let attempt = 0; attempt < GATEWAY_PROBE_MAX_ATTEMPTS; attempt += 1) {
|
||||
if (await probeGatewayAlive()) {
|
||||
gatewayReadyResolved = true;
|
||||
markApiGatewayReady();
|
||||
return;
|
||||
}
|
||||
if (attempt + 1 < GATEWAY_PROBE_MAX_ATTEMPTS) {
|
||||
await sleep(GATEWAY_PROBE_DELAY_MS * (attempt + 1));
|
||||
await sleep(Math.min(GATEWAY_PROBE_BASE_DELAY_MS + attempt * 280, 2800));
|
||||
}
|
||||
}
|
||||
|
||||
throw new ApiError('Сервер API временно недоступен. Попробуйте обновить страницу.', 503, 'GATEWAY_UNAVAILABLE');
|
||||
}
|
||||
|
||||
/** Один общий прогрев: до 4 проб /health, без бесконечного цикла. */
|
||||
/** Один общий прогрев: все apiFetch ждут успешный /health, без раннего «fail-open». */
|
||||
export async function ensureApiGatewayReady(force = false): Promise<void> {
|
||||
if (typeof window === 'undefined') return;
|
||||
if (gatewayReadyResolved && !force) return;
|
||||
@@ -749,7 +788,7 @@ export async function ensureApiGatewayReady(force = false): Promise<void> {
|
||||
}
|
||||
|
||||
function gatewayRetryDelay(attempt: number): number {
|
||||
return 700 + attempt * 400;
|
||||
return 800 + attempt * 700;
|
||||
}
|
||||
|
||||
/** Повтор при кратковременном 502/503/504 (nginx не достучался до api-gateway после перезапуска). */
|
||||
@@ -783,6 +822,8 @@ export async function apiFetch<T>(path: string, options: RequestInit = {}, token
|
||||
await ensureApiGatewayReady();
|
||||
}
|
||||
|
||||
await acquireApiSlot();
|
||||
|
||||
const resolvedToken = resolveAccessToken(token);
|
||||
const method = (options.method ?? 'GET').toUpperCase();
|
||||
const hasBody = options.body !== undefined && options.body !== null;
|
||||
@@ -796,40 +837,45 @@ export async function apiFetch<T>(path: string, options: RequestInit = {}, token
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetchWithGatewayRetry(`${getApiUrl()}${path}`, {
|
||||
...options,
|
||||
headers
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
throw error;
|
||||
}
|
||||
throw mapFetchError(error);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await parseErrorResponse(response);
|
||||
|
||||
if (error.code === 'PIN_REQUIRED') {
|
||||
notifyPinRequired(error.sessionId ?? window.localStorage.getItem(AUTH_SESSION_KEY) ?? '');
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (allowRetry && resolvedToken && error.code === 'TOKEN_EXPIRED') {
|
||||
const refreshed = await trySilentTokenRefresh();
|
||||
if (refreshed?.accessToken) {
|
||||
return apiFetch<T>(path, options, refreshed.accessToken, false);
|
||||
}
|
||||
if (refreshed?.requiresPin) {
|
||||
try {
|
||||
response = await fetchWithGatewayRetry(`${getApiUrl()}${path}`, {
|
||||
...options,
|
||||
headers
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof ApiError) {
|
||||
throw error;
|
||||
}
|
||||
throw mapFetchError(error);
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
if (!response.ok) {
|
||||
const error = await parseErrorResponse(response);
|
||||
|
||||
markApiGatewayReady();
|
||||
return response.json() as Promise<T>;
|
||||
if (error.code === 'PIN_REQUIRED') {
|
||||
notifyPinRequired(error.sessionId ?? window.localStorage.getItem(AUTH_SESSION_KEY) ?? '');
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (allowRetry && resolvedToken && error.code === 'TOKEN_EXPIRED') {
|
||||
const refreshed = await trySilentTokenRefresh();
|
||||
if (refreshed?.accessToken) {
|
||||
releaseApiSlot();
|
||||
return apiFetch<T>(path, options, refreshed.accessToken, false);
|
||||
}
|
||||
if (refreshed?.requiresPin) {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
|
||||
markApiGatewayReady();
|
||||
return response.json() as Promise<T>;
|
||||
} finally {
|
||||
releaseApiSlot();
|
||||
}
|
||||
}
|
||||
|
||||
export { getDeviceFingerprint, buildAuthDevicePayload, resolveDeviceLabel, formatUserAgentLabel } from '@/lib/device-client';
|
||||
|
||||
Reference in New Issue
Block a user