fix and update
This commit is contained in:
@@ -11,6 +11,7 @@ import {
|
|||||||
AUTH_USER_CACHE_KEY,
|
AUTH_USER_CACHE_KEY,
|
||||||
AuthSessionResponse,
|
AuthSessionResponse,
|
||||||
AuthTokens,
|
AuthTokens,
|
||||||
|
ensureApiGatewayReady,
|
||||||
fetchAuthSession,
|
fetchAuthSession,
|
||||||
getDeviceFingerprint,
|
getDeviceFingerprint,
|
||||||
IdentifyResponse,
|
IdentifyResponse,
|
||||||
@@ -159,10 +160,10 @@ export function AuthProvider({ children }: { children: React.ReactNode }) {
|
|||||||
cacheUserProfile(auth.user);
|
cacheUserProfile(auth.user);
|
||||||
setHasStoredSession(true);
|
setHasStoredSession(true);
|
||||||
clearPinLock();
|
clearPinLock();
|
||||||
|
setIsLoading(true);
|
||||||
|
void ensureApiGatewayReady().finally(() => setIsLoading(false));
|
||||||
if (auth.pinVerified !== false) {
|
if (auth.pinVerified !== false) {
|
||||||
window.setTimeout(() => {
|
void syncFedcmSession(auth.accessToken);
|
||||||
void syncFedcmSession(auth.accessToken);
|
|
||||||
}, 300);
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
[clearPinLock]
|
[clearPinLock]
|
||||||
@@ -255,6 +256,16 @@ 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) {
|
||||||
|
try {
|
||||||
|
await ensureApiGatewayReady();
|
||||||
|
} catch {
|
||||||
|
// Продолжаем даже если gateway не ответил в срок прогрева.
|
||||||
|
}
|
||||||
|
}
|
||||||
setIsLoading(false);
|
setIsLoading(false);
|
||||||
refreshInFlightRef.current = null;
|
refreshInFlightRef.current = null;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,7 @@ function formatTime(value: string) {
|
|||||||
|
|
||||||
export function NotificationBell() {
|
export function NotificationBell() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { token, isPinLocked } = useAuth();
|
const { token, isPinLocked, isLoading } = useAuth();
|
||||||
const { showToast } = useToast();
|
const { showToast } = useToast();
|
||||||
const { unreadCount, setUnreadCount, subscribe } = useRealtime();
|
const { unreadCount, setUnreadCount, subscribe } = useRealtime();
|
||||||
const [open, setOpen] = useState(false);
|
const [open, setOpen] = useState(false);
|
||||||
@@ -36,7 +36,7 @@ export function NotificationBell() {
|
|||||||
const [respondingId, setRespondingId] = useState<string | null>(null);
|
const [respondingId, setRespondingId] = useState<string | null>(null);
|
||||||
|
|
||||||
const load = useCallback(async () => {
|
const load = useCallback(async () => {
|
||||||
if (!token || isPinLocked) return;
|
if (!token || isPinLocked || isLoading) return;
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
try {
|
try {
|
||||||
const [list, count] = await Promise.all([fetchNotifications(token), fetchUnreadNotificationCount(token)]);
|
const [list, count] = await Promise.all([fetchNotifications(token), fetchUnreadNotificationCount(token)]);
|
||||||
@@ -48,7 +48,7 @@ export function NotificationBell() {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [isPinLocked, setUnreadCount, showToast, token]);
|
}, [isLoading, isPinLocked, setUnreadCount, showToast, token]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void load();
|
void load();
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import * as React from 'react';
|
import * as React from 'react';
|
||||||
import { useAuth } from '@/components/id/auth-provider';
|
import { useAuth } from '@/components/id/auth-provider';
|
||||||
import { getWsUrl, type ChatMessage } from '@/lib/api';
|
import { ensureApiGatewayReady, getWsUrl, type ChatMessage } from '@/lib/api';
|
||||||
import { dispatchAvatarUpdated, dispatchChatRoomAvatarUpdated } from '@/lib/avatar-events';
|
import { dispatchAvatarUpdated, dispatchChatRoomAvatarUpdated } from '@/lib/avatar-events';
|
||||||
|
|
||||||
export interface RealtimeEvent {
|
export interface RealtimeEvent {
|
||||||
@@ -31,7 +31,7 @@ interface RealtimeContextValue {
|
|||||||
const RealtimeContext = React.createContext<RealtimeContextValue | null>(null);
|
const RealtimeContext = React.createContext<RealtimeContextValue | null>(null);
|
||||||
|
|
||||||
export function RealtimeProvider({ children }: { children: React.ReactNode }) {
|
export function RealtimeProvider({ children }: { children: React.ReactNode }) {
|
||||||
const { user, token, isPinLocked } = useAuth();
|
const { user, token, isPinLocked, isLoading } = useAuth();
|
||||||
const [unreadCount, setUnreadCount] = React.useState(0);
|
const [unreadCount, setUnreadCount] = React.useState(0);
|
||||||
const [connected, setConnected] = React.useState(false);
|
const [connected, setConnected] = React.useState(false);
|
||||||
const listenersRef = React.useRef(new Set<Listener>());
|
const listenersRef = React.useRef(new Set<Listener>());
|
||||||
@@ -48,7 +48,7 @@ export function RealtimeProvider({ children }: { children: React.ReactNode }) {
|
|||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
React.useEffect(() => {
|
React.useEffect(() => {
|
||||||
if (!user || !token || isPinLocked) {
|
if (!user || !token || isPinLocked || isLoading) {
|
||||||
socketRef.current?.close();
|
socketRef.current?.close();
|
||||||
socketRef.current = null;
|
socketRef.current = null;
|
||||||
setConnected(false);
|
setConnected(false);
|
||||||
@@ -57,7 +57,13 @@ export function RealtimeProvider({ children }: { children: React.ReactNode }) {
|
|||||||
|
|
||||||
let cancelled = false;
|
let cancelled = false;
|
||||||
|
|
||||||
function connect() {
|
async function connect() {
|
||||||
|
if (cancelled) return;
|
||||||
|
try {
|
||||||
|
await ensureApiGatewayReady();
|
||||||
|
} catch {
|
||||||
|
// Пробуем подключиться даже если health не ответил в срок.
|
||||||
|
}
|
||||||
if (cancelled) return;
|
if (cancelled) return;
|
||||||
const url = `${getWsUrl()}?token=${encodeURIComponent(token!)}`;
|
const url = `${getWsUrl()}?token=${encodeURIComponent(token!)}`;
|
||||||
const socket = new WebSocket(url);
|
const socket = new WebSocket(url);
|
||||||
@@ -105,7 +111,7 @@ export function RealtimeProvider({ children }: { children: React.ReactNode }) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
connect();
|
void connect();
|
||||||
|
|
||||||
return () => {
|
return () => {
|
||||||
cancelled = true;
|
cancelled = true;
|
||||||
@@ -114,7 +120,7 @@ export function RealtimeProvider({ children }: { children: React.ReactNode }) {
|
|||||||
socketRef.current = null;
|
socketRef.current = null;
|
||||||
setConnected(false);
|
setConnected(false);
|
||||||
};
|
};
|
||||||
}, [emit, isPinLocked, token, user]);
|
}, [emit, isLoading, isPinLocked, token, user]);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<RealtimeContext.Provider value={{ unreadCount, setUnreadCount, subscribe, connected }}>
|
<RealtimeContext.Provider value={{ unreadCount, setUnreadCount, subscribe, connected }}>
|
||||||
|
|||||||
@@ -11,11 +11,11 @@ interface AvatarAccessResponse {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function useAvatarUrl(userId: string | undefined, hasAvatar: boolean | undefined, token: string | null) {
|
export function useAvatarUrl(userId: string | undefined, hasAvatar: boolean | undefined, token: string | null) {
|
||||||
const { isPinLocked } = useAuth();
|
const { isPinLocked, isLoading } = useAuth();
|
||||||
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
|
const [avatarUrl, setAvatarUrl] = useState<string | null>(null);
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
if (!userId || !token || !hasAvatar || isPinLocked) {
|
if (!userId || !token || !hasAvatar || isPinLocked || isLoading) {
|
||||||
setAvatarUrl(null);
|
setAvatarUrl(null);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
@@ -25,7 +25,7 @@ export function useAvatarUrl(userId: string | undefined, hasAvatar: boolean | un
|
|||||||
} catch {
|
} catch {
|
||||||
setAvatarUrl(null);
|
setAvatarUrl(null);
|
||||||
}
|
}
|
||||||
}, [hasAvatar, isPinLocked, token, userId]);
|
}, [hasAvatar, isLoading, isPinLocked, token, userId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
void refresh();
|
void refresh();
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
|
import { useAuth } from '@/components/id/auth-provider';
|
||||||
import { ChatMessage, ChatRoom, fetchUserE2EPublicKey, setUserE2EPublicKey } from '@/lib/api';
|
import { ChatMessage, ChatRoom, fetchUserE2EPublicKey, setUserE2EPublicKey } from '@/lib/api';
|
||||||
import { ensureE2EKeyPair } from '@/lib/e2e-crypto';
|
import { ensureE2EKeyPair } from '@/lib/e2e-crypto';
|
||||||
import {
|
import {
|
||||||
@@ -51,6 +52,7 @@ export function useE2EChat(options: {
|
|||||||
userId?: string;
|
userId?: string;
|
||||||
token?: string | null;
|
token?: string | null;
|
||||||
}) {
|
}) {
|
||||||
|
const { isLoading } = useAuth();
|
||||||
const isE2E = options.room?.type === 'E2E';
|
const isE2E = options.room?.type === 'E2E';
|
||||||
const peerUserId = useMemo(
|
const peerUserId = useMemo(
|
||||||
() => resolveChatPeerUserId(options.room, options.userId),
|
() => resolveChatPeerUserId(options.room, options.userId),
|
||||||
@@ -63,7 +65,7 @@ export function useE2EChat(options: {
|
|||||||
const [e2eErrors, setE2eErrors] = useState<Record<string, string>>({});
|
const [e2eErrors, setE2eErrors] = useState<Record<string, string>>({});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!options.userId || !options.token) return;
|
if (!options.userId || !options.token || isLoading) return;
|
||||||
void (async () => {
|
void (async () => {
|
||||||
try {
|
try {
|
||||||
const { publicKey } = await ensureE2EKeyPair(options.userId!);
|
const { publicKey } = await ensureE2EKeyPair(options.userId!);
|
||||||
@@ -72,7 +74,7 @@ export function useE2EChat(options: {
|
|||||||
// фоновая инициализация E2E
|
// фоновая инициализация E2E
|
||||||
}
|
}
|
||||||
})();
|
})();
|
||||||
}, [options.token, options.userId]);
|
}, [isLoading, options.token, options.userId]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!isE2E || !peerUserId || !options.token) {
|
if (!isE2E || !peerUserId || !options.token) {
|
||||||
|
|||||||
@@ -12,7 +12,7 @@ import {
|
|||||||
} from '@/lib/api';
|
} from '@/lib/api';
|
||||||
|
|
||||||
export function useSelectedFamily(enabled = true) {
|
export function useSelectedFamily(enabled = true) {
|
||||||
const { user, token, isPinLocked } = useAuth();
|
const { user, token, isPinLocked, isLoading } = useAuth();
|
||||||
const { selectedGroupId, setSelectedGroupId } = useFamilyOverlay();
|
const { selectedGroupId, setSelectedGroupId } = useFamilyOverlay();
|
||||||
const [groups, setGroups] = useState<FamilyGroup[]>([]);
|
const [groups, setGroups] = useState<FamilyGroup[]>([]);
|
||||||
const [group, setGroup] = useState<FamilyGroup | null>(null);
|
const [group, setGroup] = useState<FamilyGroup | null>(null);
|
||||||
@@ -20,7 +20,7 @@ export function useSelectedFamily(enabled = true) {
|
|||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(true);
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
if (!enabled || !user || !token || isPinLocked) {
|
if (!enabled || !user || !token || isPinLocked || isLoading) {
|
||||||
setGroups([]);
|
setGroups([]);
|
||||||
setGroup(null);
|
setGroup(null);
|
||||||
setPresenceMembers([]);
|
setPresenceMembers([]);
|
||||||
@@ -60,7 +60,7 @@ export function useSelectedFamily(enabled = true) {
|
|||||||
} finally {
|
} finally {
|
||||||
setLoading(false);
|
setLoading(false);
|
||||||
}
|
}
|
||||||
}, [enabled, isPinLocked, selectedGroupId, setSelectedGroupId, token, user]);
|
}, [enabled, isLoading, isPinLocked, selectedGroupId, setSelectedGroupId, token, user]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setLoading(true);
|
setLoading(true);
|
||||||
@@ -68,10 +68,10 @@ export function useSelectedFamily(enabled = true) {
|
|||||||
}, [refresh]);
|
}, [refresh]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!enabled || !token || isPinLocked || !group) return;
|
if (!enabled || !token || isPinLocked || isLoading || !group) return;
|
||||||
const timer = window.setInterval(() => void refresh(), 25_000);
|
const timer = window.setInterval(() => void refresh(), 25_000);
|
||||||
return () => window.clearInterval(timer);
|
return () => window.clearInterval(timer);
|
||||||
}, [enabled, group, isPinLocked, refresh, token]);
|
}, [enabled, group, isLoading, isPinLocked, refresh, token]);
|
||||||
|
|
||||||
const presenceByUserId = useMemo(
|
const presenceByUserId = useMemo(
|
||||||
() => new Map(presenceMembers.map((member) => [member.userId, member])),
|
() => new Map(presenceMembers.map((member) => [member.userId, member])),
|
||||||
|
|||||||
@@ -434,8 +434,13 @@ export function isPinRequiredError(error: unknown): error is ApiError {
|
|||||||
return error instanceof ApiError && error.code === 'PIN_REQUIRED';
|
return error instanceof ApiError && error.code === 'PIN_REQUIRED';
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function isGatewayUnavailableError(error: unknown): boolean {
|
||||||
|
return error instanceof ApiError && [502, 503, 504].includes(error.status);
|
||||||
|
}
|
||||||
|
|
||||||
export function getApiErrorMessage(error: unknown, fallback: string): string | null {
|
export function getApiErrorMessage(error: unknown, fallback: string): string | null {
|
||||||
if (isPinRequiredError(error)) return null;
|
if (isPinRequiredError(error)) return null;
|
||||||
|
if (isGatewayUnavailableError(error)) return null;
|
||||||
if (error instanceof ApiError && error.status === 403 && error.message.toLowerCase().includes('pin')) {
|
if (error instanceof ApiError && error.status === 403 && error.message.toLowerCase().includes('pin')) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
@@ -522,6 +527,7 @@ export async function refreshAuthSession(): Promise<RefreshSessionResponse> {
|
|||||||
export async function syncFedcmSession(accessToken: string) {
|
export async function syncFedcmSession(accessToken: string) {
|
||||||
if (typeof window === 'undefined' || !accessToken.trim()) return;
|
if (typeof window === 'undefined' || !accessToken.trim()) return;
|
||||||
try {
|
try {
|
||||||
|
await ensureApiGatewayReady();
|
||||||
await fetchWithGatewayRetry(`${getApiUrl()}/fedcm/session/sync`, {
|
await fetchWithGatewayRetry(`${getApiUrl()}/fedcm/session/sync`, {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: { Authorization: `Bearer ${accessToken.trim()}` },
|
headers: { Authorization: `Bearer ${accessToken.trim()}` },
|
||||||
@@ -625,12 +631,58 @@ 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 = 4;
|
const GATEWAY_RETRY_ATTEMPTS = 6;
|
||||||
|
const GATEWAY_WARMUP_MAX_ATTEMPTS = 24;
|
||||||
|
const GATEWAY_WARMUP_DELAY_MS = 300;
|
||||||
|
|
||||||
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));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let gatewayReadyResolved = false;
|
||||||
|
let gatewayReadyPromise: Promise<void> | null = null;
|
||||||
|
|
||||||
|
export function resetApiGatewayWarmup() {
|
||||||
|
gatewayReadyResolved = false;
|
||||||
|
gatewayReadyPromise = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function markApiGatewayReady() {
|
||||||
|
gatewayReadyResolved = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function probeGatewayHealth(): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${getApiUrl()}/health`, {
|
||||||
|
method: 'GET',
|
||||||
|
cache: 'no-store'
|
||||||
|
});
|
||||||
|
return response.ok;
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Ждёт готовности api-gateway (кратковременные 502 после перезапуска nginx/upstream). */
|
||||||
|
export async function ensureApiGatewayReady(force = false): Promise<void> {
|
||||||
|
if (typeof window === 'undefined') return;
|
||||||
|
if (gatewayReadyResolved && !force) return;
|
||||||
|
if (gatewayReadyPromise && !force) return gatewayReadyPromise;
|
||||||
|
|
||||||
|
gatewayReadyPromise = (async () => {
|
||||||
|
for (let attempt = 0; attempt < GATEWAY_WARMUP_MAX_ATTEMPTS; attempt++) {
|
||||||
|
if (await probeGatewayHealth()) {
|
||||||
|
gatewayReadyResolved = true;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
await sleep(GATEWAY_WARMUP_DELAY_MS);
|
||||||
|
}
|
||||||
|
gatewayReadyResolved = true;
|
||||||
|
})();
|
||||||
|
|
||||||
|
return gatewayReadyPromise;
|
||||||
|
}
|
||||||
|
|
||||||
/** Повтор при кратковременном 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;
|
||||||
@@ -655,6 +707,10 @@ async function fetchWithGatewayRetry(url: string, init: RequestInit): Promise<Re
|
|||||||
}
|
}
|
||||||
|
|
||||||
export async function apiFetch<T>(path: string, options: RequestInit = {}, token?: string | null, allowRetry = true): Promise<T> {
|
export async function apiFetch<T>(path: string, options: RequestInit = {}, token?: string | null, allowRetry = true): Promise<T> {
|
||||||
|
if (typeof window !== 'undefined' && path !== '/health' && !path.startsWith('/health?')) {
|
||||||
|
await ensureApiGatewayReady();
|
||||||
|
}
|
||||||
|
|
||||||
const resolvedToken = token ?? (typeof window !== 'undefined' ? window.localStorage.getItem(AUTH_TOKEN_KEY) : null);
|
const resolvedToken = token ?? (typeof window !== 'undefined' ? window.localStorage.getItem(AUTH_TOKEN_KEY) : null);
|
||||||
const method = (options.method ?? 'GET').toUpperCase();
|
const method = (options.method ?? 'GET').toUpperCase();
|
||||||
const hasBody = options.body !== undefined && options.body !== null;
|
const hasBody = options.body !== undefined && options.body !== null;
|
||||||
|
|||||||
Reference in New Issue
Block a user