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

refactor: Staggered network requests for 0.5 #101

Merged
merged 2 commits into from
Jul 18, 2023
Merged
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
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [unreleased]

## [0.5.1] - 2023-07-18

- Refactor logic for making network requests

## [0.5.0] - 2023-03-29

- Adds telemetry to the dashboard
Expand Down
2 changes: 1 addition & 1 deletion build/static/js/bundle.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion build/static/js/bundle.js.map

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package-lock.json

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

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "dashboard",
"version": "0.5.0",
"version": "0.5.1",
"private": true,
"dependencies": {
"@babel/core": "^7.16.0",
Expand Down
113 changes: 86 additions & 27 deletions src/services/network.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,41 @@ import { HttpMethod } from "../types";
* License for the specific language governing permissions and limitations
* under the License.
*/
class RequestQueueManager {
static requestQueue: { [key: string]: () => Promise<Response> } = {};
static waiters: { [key: string]: (response: Response) => void } = {};
static isProcessing = false;

static addRequestToQueue(request: () => Promise<Response>, waiter: (response: Response) => void): string {
const id = `${Date.now()}.${Math.floor(Math.random() * 1000)}`;
RequestQueueManager.requestQueue[id] = request;
RequestQueueManager.waiters[id] = waiter;
void this.processRequest();
return id;
}

static async processRequest() {
if (RequestQueueManager.isProcessing) {
return;
}

if (Object.keys(RequestQueueManager.requestQueue).length === 0) {
return;
}

RequestQueueManager.isProcessing = true;
const requestId = Object.keys(RequestQueueManager.requestQueue)[0];
const request = RequestQueueManager.requestQueue[requestId];
const waiter = RequestQueueManager.waiters[requestId];
delete RequestQueueManager.requestQueue[requestId];
delete RequestQueueManager.waiters[requestId];

const response = await request();
waiter(response);
RequestQueueManager.isProcessing = false;
void RequestQueueManager.processRequest();
}
}
export default class NetworkManager {
static async doRequest({
url,
Expand All @@ -26,37 +61,61 @@ export default class NetworkManager {
query?: { [key: string]: string };
config?: RequestInit;
}) {
if (method === "GET") {
return this.get(url, query, config);
}
const queuedRequestFunction = () => {
if (method === "GET") {
return this.get(url, query, config);
}

if (method === "DELETE") {
return this.delete(url, query, config);
}
if (method === "DELETE") {
return this.delete(url, query, config);
}

/**
* If the user's backend has a validation for the request body being missing, it is
* possible that it will fail for some of the dashboard requests (for example api
* key validation).
*
* This ensures that a body is always sent to the server even if the API itself does
* not consume it
*/
let bodyToUse: BodyInit = JSON.stringify({});

if (config !== undefined && config.body !== null && config.body !== undefined) {
bodyToUse = config.body;
}
/**
* If the user's backend has a validation for the request body being missing, it is
* possible that it will fail for some of the dashboard requests (for example api
* key validation).
*
* This ensures that a body is always sent to the server even if the API itself does
* not consume it
*/
let bodyToUse: BodyInit = JSON.stringify({});

return fetch(new URL(url), {
...config,
body: bodyToUse,
method,
headers: {
...config?.headers,
"Content-Type": "application/json",
},
if (config !== undefined && config.body !== null && config.body !== undefined) {
bodyToUse = config.body;
}

return fetch(new URL(url), {
...config,
body: bodyToUse,
method,
headers: {
...config?.headers,
"Content-Type": "application/json",
},
});
};

let requestCompleted = false;
let response: Response;

RequestQueueManager.addRequestToQueue(queuedRequestFunction, (_response) => {
requestCompleted = true;
response = _response;
});

const waitForResponse = async () => {
while (!requestCompleted) {
await new Promise((resolve) => {
setTimeout(resolve, 10);
});
}
};

await waitForResponse();

// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
return response;
}

private static async get(url: string, query?: { [key: string]: string }, config?: RequestInit) {
Expand Down
44 changes: 44 additions & 0 deletions src/ui/components/userDetail/context/UserDetailContext.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/* Copyright (c) 2022, VRAI Labs and/or its affiliates. All rights reserved.
*
* This software is licensed under the Apache License, Version 2.0 (the
* "License") as published by the Apache Software Foundation.
*
* You may not use this file except in compliance with the License. You may
* obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import { PropsWithChildren, createContext, useContext } from "react";

type UserDetailContextType = {
showLoadingOverlay: () => void;
hideLoadingOverlay: () => void;
};

type IncomingProps = {
showLoadingOverlay: () => void;
hideLoadingOverlay: () => void;
};

type Props = PropsWithChildren<IncomingProps>;

const UserDetailContext = createContext<UserDetailContextType | undefined>(undefined);

export const useUserDetailContext = () => {
const context = useContext(UserDetailContext);
if (!context) throw "Context must be used within a provider!";
return context;
};

export const UserDetailContextProvider: React.FC<Props> = (props: Props) => {
return (
<UserDetailContext.Provider
value={{ showLoadingOverlay: props.showLoadingOverlay, hideLoadingOverlay: props.hideLoadingOverlay }}>
{props.children}
</UserDetailContext.Provider>
);
};
63 changes: 63 additions & 0 deletions src/ui/components/userDetail/userDetail.scss
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,69 @@
$container-padding-horizontal: 40;
$container-width: 829;

.user-detail-page-loader {
min-height: 80vh;
display: flex;
justify-content: center;
align-items: center;
}

.full-screen-loading-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.4);
z-index: 1;
display: flex;
justify-content: center;
align-items: center;
}

.loader-container {
background-color: var(--color-window-bg);
padding: 2px;
display: flex;
border-radius: 50%;
}

.loader {
border: 16px solid #f3f3f3; /* Light grey */
border-top: 16px solid #ff9933; /* Blue */
border-radius: 50%;
width: 60px;
height: 60px;
animation: spin 2s linear infinite;
}

@keyframes spin {
0% {
transform: rotate(0deg);
}
100% {
transform: rotate(360deg);
}
}

@-webkit-keyframes spin {
0% {
-webkit-transform: rotate(0deg);
}
100% {
-webkit-transform: rotate(360deg);
}
}

@-moz-keyframes spin {
0% {
-moz-transform: rotate(0deg);
}
100% {
-moz-transform: rotate(360deg);
}
}

.user-detail {
--badge-bg-color: rgb(197, 224, 253);
--copy-text-color: rgb(214, 80, 120);
Expand Down
93 changes: 59 additions & 34 deletions src/ui/components/userDetail/userDetail.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { getImageUrl, getRecipeNameFromid } from "../../../utils";
import { PopupContentContext } from "../../contexts/PopupContentContext";
import { EmailVerificationStatus, UserRecipeType, UserWithRecipeId } from "../../pages/usersList/types";
import { OnSelectUserFunction } from "../usersListTable/UsersListTable";
import { UserDetailContextProvider } from "./context/UserDetailContext";
import "./userDetail.scss";
import { getUpdateUserToast } from "./userDetailForm";
import UserDetailHeader from "./userDetailHeader";
Expand All @@ -47,6 +48,7 @@ export const UserDetail: React.FC<UserDetailProps> = (props) => {
const [emailVerificationStatus, setEmailVerificationStatus] = useState<EmailVerificationStatus | undefined>(
undefined
);
const [shouldShowLoadingOverlay, setShowLoadingOverlay] = useState<boolean>(false);

const { getUser, updateUserInformation } = useUserService();

Expand Down Expand Up @@ -128,8 +130,20 @@ export const UserDetail: React.FC<UserDetailProps> = (props) => {
await fetchEmailVerificationStatus();
};

const showLoadingOverlay = () => {
setShowLoadingOverlay(true);
};

const hideLoadingOverlay = () => {
setShowLoadingOverlay(false);
};

if (userDetail === undefined) {
return <></>;
return (
<div className="user-detail-page-loader">
<div className="loader"></div>
</div>
);
}

if (userDetail.status === "NO_USER_FOUND_ERROR") {
Expand Down Expand Up @@ -161,40 +175,51 @@ export const UserDetail: React.FC<UserDetailProps> = (props) => {
}

return (
<div className="user-detail">
<div className="user-detail__navigation">
<button
className="button flat"
onClick={onBackButtonClicked}>
<img
src={getImageUrl("left-arrow-dark.svg")}
alt="Back to all users"
/>
<span>Back to all users</span>
</button>
<UserDetailContextProvider
showLoadingOverlay={showLoadingOverlay}
hideLoadingOverlay={hideLoadingOverlay}>
<div className="user-detail">
{shouldShowLoadingOverlay && (
<div className="full-screen-loading-overlay">
<div className="loader-container">
<div className="loader"></div>
</div>
</div>
)}
<div className="user-detail__navigation">
<button
className="button flat"
onClick={onBackButtonClicked}>
<img
src={getImageUrl("left-arrow-dark.svg")}
alt="Back to all users"
/>
<span>Back to all users</span>
</button>
</div>
<UserDetailHeader
userDetail={userDetail.user}
{...props}
/>
<UserDetailInfoGrid
userDetail={userDetail.user}
refetchData={refetchAllData}
onUpdateCallback={updateUser}
emailVerificationStatus={emailVerificationStatus}
{...props}
/>
<UserMetaDataSection
metadata={userMetaData}
userId={user}
refetchData={refetchAllData}
/>

<UserDetailsSessionList
sessionList={sessionList}
refetchData={refetchAllData}
/>
</div>
<UserDetailHeader
userDetail={userDetail.user}
{...props}
/>
<UserDetailInfoGrid
userDetail={userDetail.user}
refetchData={refetchAllData}
onUpdateCallback={updateUser}
emailVerificationStatus={emailVerificationStatus}
{...props}
/>
<UserMetaDataSection
metadata={userMetaData}
userId={user}
refetchData={refetchAllData}
/>

<UserDetailsSessionList
sessionList={sessionList}
refetchData={refetchAllData}
/>
</div>
</UserDetailContextProvider>
);
};

Expand Down
Loading
Loading