This commit is contained in:
2025-05-20 04:16:03 +03:00
parent 21a05dd202
commit 9531bff01a
88 changed files with 7797 additions and 2246 deletions

View File

@@ -1,47 +1,42 @@
import { useQueryClient } from '@tanstack/react-query';
import { useEffect } from 'react';
import { useGatewayWebSocketStore } from '~/store/gateway-websocket';
import { useTokenStore } from '~/store/token';
import { ConnectionState } from '~/lib/websocket/gateway/types';
import { useGatewayStore } from '~/stores/gateway-store';
import { useTokenStore } from '~/stores/token-store';
export function GatewayWebSocketConnectionManager() {
const connectWebSocket = useGatewayWebSocketStore((state) => state.connect);
const disconnectWebSocket = useGatewayWebSocketStore((state) => state.disconnect);
const wsStatus = useGatewayWebSocketStore((state) => state.status);
const token = useTokenStore((state) =>
state.token,
);
const { setQueryClient } = useGatewayStore();
const queryClient = useQueryClient();
useEffect(() => {
console.debug(`WS Manager: Status (${wsStatus})`);
setQueryClient(queryClient);
}, [queryClient])
useEffect(() => {
const { status, connect, disconnect } = useGatewayStore.getState();
if (!!token) {
// Connect if we should be connected and are currently idle, disconnected, or errored out
if (wsStatus === 'IDLE' || wsStatus === 'DISCONNECTED' || wsStatus === 'ERROR') {
console.log("WS Manager: Conditions met. Calling connect...");
// Pass the stable token getter function reference
connectWebSocket(() => token);
}
connect(token);
} else {
// Disconnect if we shouldn't be connected and are currently in any connected/connecting state
if (wsStatus !== 'IDLE' && wsStatus !== 'DISCONNECTED') {
console.log("WS Manager: Conditions no longer met. Calling disconnect...");
disconnectWebSocket(true); // Intentional disconnect
if (status === ConnectionState.CONNECTED) {
disconnect();
}
}
// The disconnect logic for component unmount (e.g., user logs out entirely)
return () => {
// Check status on unmount to avoid disconnecting if already idle/disconnected
const currentStatus = useGatewayWebSocketStore.getState().status;
if (currentStatus !== 'IDLE' && currentStatus !== 'DISCONNECTED') {
console.log("WS Manager: Unmounting. Calling disconnect...");
// Ensure Zustand has the latest state before calling disconnect
useGatewayWebSocketStore.getState().disconnect(true); // Intentional disconnect on unmount
if (status === ConnectionState.CONNECTED) {
disconnect();
}
};
// Dependencies: connect/disconnect actions, auth status, route location
}, [connectWebSocket, disconnectWebSocket]);
}, [token]);
// This component doesn't render anything itself
return null;
return (
<>
{null}
</>
);
}