Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reset store without reconnecting socket #898

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 10 additions & 23 deletions liwords-ui/src/App.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import React, { useCallback, useEffect, useRef } from 'react';
import { Route, Switch, useLocation, Redirect } from 'react-router-dom';
import { useMountedState } from './utils/mounted';
import './App.scss';
import axios from 'axios';
import 'antd/dist/antd.css';
Expand All @@ -17,7 +16,7 @@ import {
useFriendsStoreContext,
} from './store/store';

import { LiwordsSocket } from './socket/socket';
import { useLiwordsSocketContext } from './socket/socket';
import { Team } from './about/team';
import { Register } from './lobby/register';
import { UserProfile } from './profile/profile';
Expand Down Expand Up @@ -66,15 +65,18 @@ if (bnjyTile) {
}

const App = React.memo(() => {
const { useState } = useMountedState();

const {
setExcludedPlayers,
setExcludedPlayersFetched,
pendingBlockRefresh,
setPendingBlockRefresh,
} = useExcludedPlayersStoreContext();

const {
liwordsSocketValues: { sendMessage },
resetLiwordsSocketStore,
} = useLiwordsSocketContext();

const { loginState } = useLoginStateStoreContext();
const { loggedIn, userID } = loginState;

Expand All @@ -90,26 +92,16 @@ const App = React.memo(() => {
setPendingFriendsRefresh,
} = useFriendsStoreContext();

const { resetStore } = useResetStoreContext();

// See store.tsx for how this works.
const [socketId, setSocketId] = useState(0);
const resetSocket = useCallback(() => setSocketId((n) => (n + 1) | 0), []);

const [liwordsSocketValues, setLiwordsSocketValues] = useState({
sendMessage: (msg: Uint8Array) => {},
justDisconnected: false,
});
const { sendMessage } = liwordsSocketValues;
const { resetRestOfStore } = useResetStoreContext();

const location = useLocation();
const knownLocation = useRef(location.pathname); // Remember the location on first render.
const isCurrentLocation = knownLocation.current === location.pathname;
useEffect(() => {
if (!isCurrentLocation) {
resetStore();
resetRestOfStore();
}
}, [isCurrentLocation, resetStore]);
}, [isCurrentLocation, resetRestOfStore]);

const getFullBlocks = useCallback(() => {
void userID; // used only as effect dependency
Expand Down Expand Up @@ -226,17 +218,12 @@ const App = React.memo(() => {

return (
<div className="App">
<LiwordsSocket
key={socketId}
resetSocket={resetSocket}
setValues={setLiwordsSocketValues}
/>
<Switch>
<Route path="/" exact>
<Lobby
sendSocketMsg={sendMessage}
sendChat={sendChat}
DISCONNECT={resetSocket}
DISCONNECT={resetLiwordsSocketStore}
/>
</Route>
<Route path="/tournament/:partialSlug">
Expand Down
6 changes: 3 additions & 3 deletions liwords-ui/src/lobby/login.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { toAPIUrl } from '../api/api';

export const Login = React.memo(() => {
const { useState } = useMountedState();
const { resetStore } = useResetStoreContext();
const { resetLoginStateStore } = useResetStoreContext();

const [err, setErr] = useState('');
const [loggedIn, setLoggedIn] = useState(false);
Expand Down Expand Up @@ -42,9 +42,9 @@ export const Login = React.memo(() => {

React.useEffect(() => {
if (loggedIn) {
resetStore();
resetLoginStateStore();
}
}, [loggedIn, resetStore]);
}, [loggedIn, resetLoginStateStore]);

return (
<div className="account">
Expand Down
6 changes: 3 additions & 3 deletions liwords-ui/src/settings/settings.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export const Settings = React.memo((props: Props) => {
const { loginState } = useLoginStateStoreContext();
const { userID, username: viewer, loggedIn } = loginState;
const { useState } = useMountedState();
const { resetStore } = useResetStoreContext();
const { resetLoginStateStore } = useResetStoreContext();
const { section } = useParams();
const [category, setCategory] = useState(
getInitialCategory(section, loggedIn)
Expand Down Expand Up @@ -170,13 +170,13 @@ export const Settings = React.memo((props: Props) => {
message: 'Success',
description: 'You have been logged out.',
});
resetStore();
resetLoginStateStore();
history.push('/');
})
.catch((e) => {
console.log(e);
});
}, [history, resetStore]);
}, [history, resetLoginStateStore]);

const updatedAvatar = useCallback(
(avatarUrl: string) => {
Expand Down
98 changes: 80 additions & 18 deletions liwords-ui/src/socket/socket.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,11 @@
import { useCallback, useEffect, useMemo, useRef } from 'react';
import {
createContext,
useCallback,
useContext,
useEffect,
useMemo,
useRef,
} from 'react';
import axios from 'axios';
import jwt from 'jsonwebtoken';
import useWebSocket from 'react-use-websocket';
Expand All @@ -7,7 +14,6 @@ import { message } from 'antd';
import { useMountedState } from '../utils/mounted';
import { useLoginStateStoreContext } from '../store/store';
import {
useOnSocketMsg,
ReverseMessageType,
enableShowSocket,
parseMsgs,
Expand All @@ -18,6 +24,42 @@ import { ActionType } from '../actions/actions';
import { reloadAction } from './reload';
import { birthdateWarning } from './birthdateWarning';

// Store-specific code.

const defaultFunction = () => {};

export type LiwordsSocketValues = {
sendMessage: (msg: Uint8Array) => void;
justDisconnected: boolean;
};

export type OnSocketMsgType = (reader: FileReader) => void;

type LiwordsSocketStoreData = {
liwordsSocketValues: LiwordsSocketValues;
onSocketMsg: OnSocketMsgType;
resetLiwordsSocketStore: () => void;
setLiwordsSocketValues: React.Dispatch<
React.SetStateAction<LiwordsSocketValues>
>;
setOnSocketMsg: React.Dispatch<React.SetStateAction<OnSocketMsgType>>;
};

export const LiwordsSocketContext = createContext<LiwordsSocketStoreData>({
liwordsSocketValues: {
sendMessage: defaultFunction,
justDisconnected: false,
},
onSocketMsg: defaultFunction,
resetLiwordsSocketStore: defaultFunction,
setLiwordsSocketValues: defaultFunction,
setOnSocketMsg: defaultFunction,
});

export const useLiwordsSocketContext = () => useContext(LiwordsSocketContext);

// Non-Store code follows.

const getSocketURI = (): string => {
const loc = window.location;
let protocol;
Expand Down Expand Up @@ -51,23 +93,36 @@ type DecodedToken = {
// Returning undefined from useEffect is fine, but some linters dislike it.
const doNothing = () => {};

export const LiwordsSocket = (props: {
resetSocket: () => void;
setValues: (_: {
sendMessage: (msg: Uint8Array) => void;
justDisconnected: boolean;
}) => void;
}): null => {
export const LiwordsSocket = (props: {}): null => {
const isMountedRef = useRef(true);
useEffect(() => () => void (isMountedRef.current = false), []);
const { useState } = useMountedState();

const { resetSocket, setValues } = props;
const onSocketMsg = useOnSocketMsg();
const {
onSocketMsg,
resetLiwordsSocketStore,
setLiwordsSocketValues,
} = useLiwordsSocketContext();

const loginStateStore = useLoginStateStoreContext();
const location = useLocation();
const { pathname } = location;
const pathname = useMemo(() => {
const originalPathname = location.pathname;
// XXX: The socket requires path to know which realms it has to connect to.
// See liwords-socket pkg/hub/hub.go RegisterRealm.
// That calls back into liwords pkg/bus/bus.go handleNatsRequest.

// It seems only a few paths matter.
if (
originalPathname.startsWith('/game/') ||
originalPathname.startsWith('/tournament/') ||
originalPathname.startsWith('/club/')
)
return originalPathname;

// For everything else, there's MasterCard.
return '/';
}, [location.pathname]);

// const [socketToken, setSocketToken] = useState('');
const [justDisconnected, setJustDisconnected] = useState(false);
Expand Down Expand Up @@ -109,8 +164,6 @@ export const LiwordsSocket = (props: {
userID: decoded.uid,
loggedIn: decoded.a,
connID: cid,
isChild: decoded.cs,
path: pathname,
perms: decoded.perms?.split(','),
},
});
Expand Down Expand Up @@ -213,12 +266,21 @@ export const LiwordsSocket = (props: {
useEffect(() => {
const t = setTimeout(() => {
console.log('reconnecting socket');
resetSocket();
resetLiwordsSocketStore();
}, 15000);
return () => {
clearTimeout(t);
};
}, [patienceId, resetSocket]);
}, [patienceId, resetLiwordsSocketStore]);

// Force reconnection when pathname materially changes.
const knownPathname = useRef(pathname); // Remember the pathname on first render.
const isCurrentPathname = knownPathname.current === pathname;
useEffect(() => {
if (!isCurrentPathname) {
resetLiwordsSocketStore();
}
}, [isCurrentPathname, resetLiwordsSocketStore]);

const { sendMessage: originalSendMessage } = useWebSocket(
getFullSocketUrlAsync,
Expand Down Expand Up @@ -271,8 +333,8 @@ export const LiwordsSocket = (props: {
justDisconnected,
]);
useEffect(() => {
setValues(ret);
}, [setValues, ret]);
setLiwordsSocketValues(ret);
}, [setLiwordsSocketValues, ret]);

return null;
};
12 changes: 3 additions & 9 deletions liwords-ui/src/store/login_state.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,15 @@
import { Action, ActionType } from '../actions/actions';

export type LoginState = {
export type AuthInfo = {
username: string;
userID: string;
loggedIn: boolean;
connID: string;
connectedToSocket: boolean;
path: string;
perms: Array<string>;
};

export type AuthInfo = {
username: string;
userID: string;
loggedIn: boolean;
connID: string;
perms: Array<string>;
export type LoginState = AuthInfo & {
connectedToSocket: boolean;
};

export function LoginStateReducer(
Expand Down
2 changes: 2 additions & 0 deletions liwords-ui/src/store/socket_handlers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -163,6 +163,8 @@ export const ReverseMessageType = (() => {
return ret;
})();

// This needs to have access to Rest Of Store.
// Therefore it cannot be used directly from LiwordsSocket.
export const useOnSocketMsg = () => {
const { challengeResultEvent } = useChallengeResultEventStoreContext();
const { addChat, deleteChat } = useChatStoreContext();
Expand Down
Loading