Skip to content

Commit

Permalink
Revert "Jim/wall 5227/switch ws connection when clients switch betwee…
Browse files Browse the repository at this point in the history
…n real a…" (#17943)

This reverts commit ac6d910.
  • Loading branch information
hirad-deriv committed Jan 7, 2025
1 parent c27ce9a commit 3ed2f0b
Show file tree
Hide file tree
Showing 7 changed files with 25 additions and 75 deletions.
31 changes: 8 additions & 23 deletions packages/api-v2/src/APIProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,10 @@
import React, { createContext, PropsWithChildren, useCallback, useContext, useEffect, useRef, useState } from 'react';

import React, { PropsWithChildren, createContext, useContext, useEffect, useRef, useState, useCallback } from 'react';
import { getAppId, getSocketURL } from '@deriv/shared';
import { getInitialLanguage } from '@deriv-com/translations';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

import { TSocketRequestPayload, TSocketResponseData, TSocketSubscribableEndpointNames } from '../types';

import WSClient from './ws-client/ws-client';
import { PLATFORMS } from './constants';
import { hashObject } from './utils';
import WSClient from './ws-client/ws-client';

type TSubscribeFunction = <T extends TSocketSubscribableEndpointNames>(
name: T,
Expand All @@ -31,14 +27,14 @@ type APIContextData = {
setOnConnected: (onConnected: () => void) => void;
connection: WebSocket;
wsClient: WSClient;
createNewWSConnection: () => void;
};

/**
* Retrieves the WebSocket URL based on the current environment.
* @returns {string} The WebSocket URL.
*/
const getWebSocketURL = (endpoint: string) => {
const getWebSocketURL = () => {
const endpoint = getSocketURL();
const app_id = getAppId();
const language = getInitialLanguage();
return `wss://${endpoint}/websockets/v3?app_id=${app_id}&l=${language}&brand=deriv`;
Expand All @@ -49,8 +45,8 @@ const APIContext = createContext<APIContextData | null>(null);
/**
* @returns {WebSocket} The initialized WebSocket instance.
*/
const initializeConnection = (endpoint: string, onWSClose: () => void, onOpen?: () => void): WebSocket => {
const wss_url = getWebSocketURL(endpoint);
const initializeConnection = (onWSClose: () => void, onOpen?: () => void): WebSocket => {
const wss_url = getWebSocketURL();

const connection = new WebSocket(wss_url);
connection.addEventListener('close', () => {
Expand All @@ -71,13 +67,12 @@ const initializeConnection = (endpoint: string, onWSClose: () => void, onOpen?:
type TAPIProviderProps = {
/** If set to true, the APIProvider will instantiate it's own socket connection. */
standalone?: boolean;
platform?: string;
};

type SubscribeReturnType = ReturnType<TSubscribeFunction>; // This captures the entire return type of TSubscribeFunction
type UnwrappedSubscription = Awaited<SubscribeReturnType>;

const APIProvider = ({ children, platform }: PropsWithChildren<TAPIProviderProps>) => {
const APIProvider = ({ children }: PropsWithChildren<TAPIProviderProps>) => {
const [reconnect, setReconnect] = useState(false);
const connectionRef = useRef<WebSocket>();
const subscriptionsRef = useRef<Record<string, UnwrappedSubscription['subscription']>>();
Expand All @@ -92,7 +87,6 @@ const APIProvider = ({ children, platform }: PropsWithChildren<TAPIProviderProps

const language = getInitialLanguage();
const [prevLanguage, setPrevLanguage] = useState<string>(language);
const endpoint = getSocketURL(platform === PLATFORMS.WALLETS);

useEffect(() => {
isMounted.current = true;
Expand All @@ -115,7 +109,6 @@ const APIProvider = ({ children, platform }: PropsWithChildren<TAPIProviderProps
// have to be here and not inside useEffect as there are places in code expecting this to be available
if (!connectionRef.current) {
connectionRef.current = initializeConnection(
endpoint,
() => {
if (isMounted.current) setReconnect(true);
},
Expand All @@ -125,7 +118,6 @@ const APIProvider = ({ children, platform }: PropsWithChildren<TAPIProviderProps
}

wsClientRef.current.setWs(connectionRef.current);
wsClientRef.current.setEndpoint(endpoint);
if (isMounted.current) {
isOpenRef.current = true;
if (onConnectedRef.current) {
Expand Down Expand Up @@ -205,7 +197,6 @@ const APIProvider = ({ children, platform }: PropsWithChildren<TAPIProviderProps
let reconnectTimerId: NodeJS.Timeout;
if (reconnect) {
connectionRef.current = initializeConnection(
endpoint,
() => {
reconnectTimerId = setTimeout(() => {
if (isMounted.current) {
Expand All @@ -218,7 +209,6 @@ const APIProvider = ({ children, platform }: PropsWithChildren<TAPIProviderProps
throw new Error('Connection is not set');
}
wsClientRef.current.setWs(connectionRef.current);
wsClientRef.current.setEndpoint(endpoint);
if (onReconnectedRef.current) {
onReconnectedRef.current();
}
Expand All @@ -228,7 +218,7 @@ const APIProvider = ({ children, platform }: PropsWithChildren<TAPIProviderProps
}

return () => clearTimeout(reconnectTimerId);
}, [endpoint, reconnect]);
}, [reconnect]);

// reconnects to latest WS url for new language only when language changes
useEffect(() => {
Expand All @@ -239,15 +229,10 @@ const APIProvider = ({ children, platform }: PropsWithChildren<TAPIProviderProps
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [language]);

const createNewWSConnection = useCallback(() => {
setReconnect(true);
}, []);

return (
<APIContext.Provider
value={{
subscribe,
createNewWSConnection,
unsubscribe,
queryClient: reactQueryRef.current,
setOnReconnected,
Expand Down
41 changes: 8 additions & 33 deletions packages/api-v2/src/AuthProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,14 +1,11 @@
import React, { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react';
import React, { createContext, useState, useContext, useCallback, useEffect, useMemo } from 'react';
import { useAPIContext } from './APIProvider';

import { getAccountsFromLocalStorage, getActiveLoginIDFromLocalStorage, getToken } from '@deriv/utils';
import { AppIDConstants } from '@deriv-com/utils';

import { TSocketRequestPayload, TSocketResponseData, TSocketSubscribableEndpointNames } from '../types';

import { useAPIContext } from './APIProvider';
import { API_ERROR_CODES } from './constants';
import useAPI from './useAPI';
import useMutation from './useMutation';
import { TSocketSubscribableEndpointNames, TSocketResponseData, TSocketRequestPayload } from '../types';
import useAPI from './useAPI';
import { API_ERROR_CODES } from './constants';

// Define the type for the context state
type AuthContextType = {
Expand All @@ -28,7 +25,6 @@ type AuthContextType = {
name: T,
payload?: TSocketRequestPayload<T>
) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
subscribe: (onData: (response: any) => void) => Promise<{ unsubscribe: () => Promise<void> }>;
};
};
Expand Down Expand Up @@ -112,7 +108,7 @@ const AuthProvider = ({ loginIDKey, children, cookieTimeout, selectDefaultAccoun

const { mutateAsync } = useMutation('authorize');

const { queryClient, setOnReconnected, setOnConnected, wsClient, createNewWSConnection } = useAPIContext();
const { queryClient, setOnReconnected, setOnConnected, wsClient } = useAPIContext();

const [isLoading, setIsLoading] = useState(true);
const [isSwitching, setIsSwitching] = useState(false);
Expand All @@ -129,7 +125,6 @@ const AuthProvider = ({ loginIDKey, children, cookieTimeout, selectDefaultAccoun
const subscribe = useCallback(
<T extends TSocketSubscribableEndpointNames>(name: T, payload?: TSocketRequestPayload<T>) => {
return {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
subscribe: (onData: (response: any) => void) => {
return wsClient?.subscribe(name, payload, onData);
},
Expand All @@ -154,15 +149,8 @@ const AuthProvider = ({ loginIDKey, children, cookieTimeout, selectDefaultAccoun
if (!activeAccount) return;

localStorage.setItem(loginIDKey ?? 'active_loginid', activeLoginID);
const isDemo = activeAccount.is_virtual;
const shouldCreateNewWSConnection =
(isDemo && wsClient?.endpoint === AppIDConstants.environments.real) ||
(!isDemo && wsClient?.endpoint === AppIDConstants.environments.demo);
if (shouldCreateNewWSConnection) {
createNewWSConnection();
}
},
[loginIDKey, wsClient?.endpoint, createNewWSConnection]
[loginIDKey]
);

useEffect(() => {
Expand Down Expand Up @@ -279,21 +267,8 @@ const AuthProvider = ({ loginIDKey, children, cookieTimeout, selectDefaultAccoun
isInitializing,
subscribe,
logout,
createNewWSConnection,
};
}, [
data,
switchAccount,
refetch,
isLoading,
isError,
isFetching,
isSuccess,
loginid,
logout,
createNewWSConnection,
subscribe,
]);
}, [data, switchAccount, refetch, isLoading, isError, isFetching, isSuccess, loginid, logout, subscribe]);

return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
};
Expand Down
1 change: 0 additions & 1 deletion packages/api-v2/src/constants/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
export * from './countries';
export * from './onfido';
export * from './errorCodes';
export * from './platforms';
1 change: 0 additions & 1 deletion packages/api-v2/src/constants/platforms.ts

This file was deleted.

16 changes: 5 additions & 11 deletions packages/api-v2/src/ws-client/ws-client.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import SubscriptionsManager from './subscriptions-manager';
import request from './request';
import {
TSocketEndpointNames,
TSocketRequestPayload,
TSocketResponse,
TSocketRequestPayload,
TSocketEndpointNames,
TSocketSubscribableEndpointNames,
} from '../../types';

import request from './request';
import SubscriptionsManager from './subscriptions-manager';

/**
* WSClient as main instance
*/
Expand All @@ -16,7 +15,6 @@ export default class WSClient {
subscriptionManager: SubscriptionsManager;
isAuthorized = false;
onAuthorized?: () => void;
endpoint?: string;

constructor(onAuthorized?: () => void) {
this.onAuthorized = onAuthorized;
Expand All @@ -30,10 +28,6 @@ export default class WSClient {
}
}

setEndpoint(endpoint: string) {
this.endpoint = endpoint;
}

private onWebsocketAuthorized() {
if (!this.ws) {
return;
Expand All @@ -53,7 +47,7 @@ export default class WSClient {
return Promise.reject(new Error('WS is not set'));
}
return request(this.ws, name, payload).then((response: TSocketResponse<TSocketEndpointNames>) => {
if ('msg_type' in response && response.msg_type === 'authorize') {
if ((response as unknown as any).msg_type === 'authorize') {
this.onWebsocketAuthorized();
}

Expand Down
8 changes: 3 additions & 5 deletions packages/shared/src/utils/config/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ export const getAppId = () => {
return app_id;
};

export const getSocketURL = (is_wallets = false) => {
export const getSocketURL = () => {
const local_storage_server_url = window.localStorage.getItem('config.server_url');
if (local_storage_server_url) return local_storage_server_url;

Expand All @@ -87,10 +87,8 @@ export const getSocketURL = (is_wallets = false) => {
const params = new URLSearchParams(document.location.search.substring(1));
active_loginid_from_url = params.get('acct1');
}
const local_storage_loginid = is_wallets
? window.localStorage.getItem('active_wallet_loginid')
: window.localStorage.getItem('active_loginid');
const loginid = local_storage_loginid || active_loginid_from_url;

const loginid = window.localStorage.getItem('active_loginid') || active_loginid_from_url;
const is_real = loginid && !/^(VRT|VRW)/.test(loginid);

const server = is_real ? 'green' : 'blue';
Expand Down
2 changes: 1 addition & 1 deletion packages/wallets/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const App: React.FC<TProps> = ({
const defaultLanguage = preferredLanguage ?? language;

return (
<APIProvider platform='wallets' standalone>
<APIProvider standalone>
<WalletsAuthProvider logout={logout}>
<TranslationProvider defaultLang={defaultLanguage} i18nInstance={i18nInstance}>
<React.Suspense fallback={<Loader />}>
Expand Down

0 comments on commit 3ed2f0b

Please sign in to comment.