Skip to content

Network optimizations #3

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

Open
wants to merge 1 commit into
base: demo-base
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
11 changes: 4 additions & 7 deletions .idea/workspace.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@types/axios-cancel": "^0.2.0",
"@types/jest": "^24.0.25",
"@types/lodash": "^4.14.149",
"@types/lru-cache": "^5.1.0",
"@types/node": "^12.12.22",
"@types/react": "^16.9.17",
"@types/react-dom": "^16.9.4",
Expand All @@ -23,6 +24,7 @@
"clsx": "^1.0.4",
"immutable": "^4.0.0-rc.12",
"lodash": "^4.17.15",
"lru-cache": "^5.1.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.3.0",
Expand Down
18 changes: 11 additions & 7 deletions src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import {Chat} from "./chat/Chat";
import {StarredMessages} from "./starred-messages/StarredMessages";
import {Grid} from "@material-ui/core";
import {useUrlSearchParams} from "use-url-search-params";
import {UserLoader} from "./user-loader/UserLoader";

function randUser() {
return Math.round(Math.random() * 2);
Expand All @@ -14,13 +15,16 @@ function App() {
const userId: number = Number(user.userId);
return (
<div>
<Grid container spacing={3}>
<Grid item xs={6}>
<Chat me={userId}/>
</Grid>
<Grid item xs={6}>
<StarredMessages me={userId}/>
</Grid>
{/*<Grid container spacing={3}>*/}
{/* <Grid item xs={6}>*/}
{/* <Chat me={userId}/>*/}
{/* </Grid>*/}
{/* <Grid item xs={6}>*/}
{/* <StarredMessages me={userId}/>*/}
{/* </Grid>*/}
{/*</Grid>*/}
<Grid>
<UserLoader />
</Grid>
</div>
)
Expand Down
38 changes: 30 additions & 8 deletions src/service/UserService.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,56 @@
import {User, UserId} from "../model/Model";
import Axios from "axios-observable";
import {map, publishReplay, refCount, retry, share} from "rxjs/operators";
import {Observable} from "rxjs";
import {map, publishReplay, refCount, retry, share, tap} from "rxjs/operators";
import {Observable, of} from "rxjs";
import {unsupported} from "../Common";
import LRU from "lru-cache";

interface ValueAndRequest<Value> {
value?: Value
request: Observable<Value>
}

interface UserService {
getUserWithId: (id: UserId) => Observable<User>
}

class UserServiceImpl implements UserService {

private readonly baseUrl = "http://localhost:5000/";
private readonly userRequests: Map<UserId, Observable<User>> = new Map();
private static readonly baseUrl = "http://localhost:5000/";
private static readonly cacheOptions = {
max: 100,
maxAge: 1000 * 60 * 60
};

private readonly userCache = new LRU<UserId, ValueAndRequest<User>>(UserServiceImpl.cacheOptions);

getUserWithId(id: UserId): Observable<User> {

if(this.userRequests.has(id))
return this.userRequests.get(id) ?? unsupported("Can't happen!");
const valueAndRequest = this.userCache.get(id);
if(valueAndRequest && valueAndRequest.value) return of(valueAndRequest.value);
if(valueAndRequest) return valueAndRequest.request;

const path = `users/?userId=${id}`;
const userRequest = Axios
.get(this.baseUrl + path)
.get(UserServiceImpl.baseUrl + path)
.pipe(
map(response => response.data),
tap(user => this.cacheUser(id, user)),
publishReplay(1),
refCount()
);
this.userRequests.set(id, userRequest);
this.userCache.set(id, {
request: userRequest
});
return userRequest;
}

private cacheUser(id: UserId, user: User) {
const valueAndRequest = this.userCache.get(id);
if(!valueAndRequest) unsupported("There must be a request cached at this point!");
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Theoretically this is a possible case so calling unsupported is not a correct approach. Instead, just return if valueAndRequest === undefined.

if(valueAndRequest.value) unsupported("Value must be undefined at this point!");
valueAndRequest.value = user;
}
}

export default new UserServiceImpl();
80 changes: 80 additions & 0 deletions src/user-loader/UserLoader.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import React, {Dispatch, Reducer, useReducer} from "react";
import {User} from "../model/Model";
import {feedbackFactory, noop, unsupported} from "../Common";
import userService from "../service/UserService";
import Container from "@material-ui/core/Container";
import {TableContainer} from "@material-ui/core";
import Paper from "@material-ui/core/Paper";
import Table from "@material-ui/core/Table";
import TableHead from "@material-ui/core/TableHead";
import TableRow from "@material-ui/core/TableRow";
import TableCell from "@material-ui/core/TableCell";
import TableBody from "@material-ui/core/TableBody";

const randomUserIds = Array.from({length: 30}, () => Math.floor(Math.random() * 5));

interface State {
users: Array<User>
}

const initialState: State = {
users: randomUserIds.map(id => ({id, name: "-"}))
};

export const UserLoader: React.FC = () => {
const [state, dispatch] = useReducer(reducer, initialState);
useFeedbacks(state, dispatch);
return (
<Container fixed maxWidth="sm">
<TableContainer component={Paper}>
<Table aria-label="simple table">
<TableHead>
<TableRow>
<TableCell>User Id</TableCell>
<TableCell>User name</TableCell>
</TableRow>
</TableHead>
<TableBody>
{state.users.map(u => (
<TableRow>
<TableCell component="th" scope="row">
{u.id}
</TableCell>
<TableCell component="th" scope="row">
{u.name}
</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</TableContainer>
</Container>
);
};


type Action = { user: User }

const reducer: Reducer<State, Action> = (state, action) => {
const index = state.users.findIndex(u => u.id === action.user.id && u.name ==="-");
if (index === -1) unsupported("The user must be in the array!");
state.users[index] = action.user;
return {users: state.users};
};

const useFeedbacks = (state: State, dispatch: Dispatch<Action>) => {
const useFeedback = feedbackFactory(state);
useFeedback(
s => s.users.map(u => u.id),
ids => {
ids.forEach(id => {
setTimeout(_ => {
userService
.getUserWithId(id)
.subscribe(user => dispatch({user}))
}, Math.random() * 10000);
});
return noop;
}
)
};