Skip to content

Commit

Permalink
CHORES: cache response by by filter
Browse files Browse the repository at this point in the history
  • Loading branch information
silvareal committed Jan 3, 2023
1 parent 4bb049a commit 61a715d
Show file tree
Hide file tree
Showing 6 changed files with 102 additions and 71 deletions.
23 changes: 5 additions & 18 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,41 +11,28 @@ function App() {
const {
servicesGroupedByName,
serversGroupedByHost,
updateCount,
connectionStatus,
sendJsonMessage,
setJsonMessage,
} = useSocket();

const [servicesGroupByName, setServicesGroupByName] = React.useState<any>({});

const [servicesGroupByHost, setServicesGroupByHost] = React.useState<any>({});

React.useEffect(() => {
setServicesGroupByName(servicesGroupedByName);
}, [updateCount]);

React.useEffect(() => {
setServicesGroupByHost(serversGroupedByHost);
}, [updateCount]);

const router = createBrowserRouter([
{
path: "/",
element: (
<ServerList
serversGroupedByHost={servicesGroupByHost}
serversGroupedByHost={serversGroupedByHost}
connectionStatus={connectionStatus}
sendJsonMessage={sendJsonMessage}
setJsonMessage={setJsonMessage}
/>
),
},
{
path: "/:host",
element: (
<ServerDetail
servicesGroupedByName={servicesGroupByName}
servicesGroupedByName={servicesGroupedByName}
connectionStatus={connectionStatus}
sendJsonMessage={sendJsonMessage}
setJsonMessage={setJsonMessage}
/>
),
},
Expand Down
77 changes: 43 additions & 34 deletions web/src/hooks/useSocket.tsx
Original file line number Diff line number Diff line change
@@ -1,77 +1,86 @@
import { useState } from 'react';
import useWebSocket, { ReadyState } from 'react-use-websocket';
import { useEffect, useState } from "react";
import useWebSocket, { ReadyState } from "react-use-websocket";
import {
ServerGroupedByHostResponseType,
ServerGroupedByNameResponseType,
ServerResponseByHostType,
ServerResponseType,
} from 'server/ServerType';
} from "server/ServerType";

const wssMetricsBaseURL = `${process.env.REACT_APP_WS_BASE_URL}/metrics`;
const wssMetricsURL = `${
window.location.protocol === 'https:' ? 'wss' : 'ws'
window.location.protocol === "https:" ? "wss" : "ws"
}://${window.location.host}/metrics`;
/*
This hook is used to connect to the websocket server and send messages to it.
*/
export default function useSocket(options = {}) {
const [servers, setServers] = useState<ServerResponseType[]>([]);
const [updateCount, setUpdateCount] = useState<number>(0);
const [servers, setServers] = useState<ServerResponseByHostType>({});
const [jsonMessage, setJsonMessage] = useState<{ [key: string]: string }>();

const serversGroupedByHost: ServerGroupedByHostResponseType = servers.reduce(
(group: any, server) => {
let serversHost: Array<ServerResponseType> =
servers[jsonMessage?.FilterBy as any] || [];

const serversGroupedByHost: ServerGroupedByHostResponseType =
serversHost.reduce((group: any, server) => {
const { Message } = server;
const { Host } = Message;
group[Host] = group[Host] ?? [];
group[Host].push(server);
return group;
},
{}
);
}, {});

const servicesGroupedByName: ServerGroupedByNameResponseType = servers.reduce(
(group: any, server: any) => {
const servicesGroupedByName: ServerGroupedByNameResponseType =
serversHost.reduce((group: any, server: any) => {
const { Message } = server;
const { Name,Host } = Message;
const { Name, Host } = Message;
group[Name] = group[Name] ?? { data: [], Host };
group[Name].data.push(server);
return group;
},
{}
);

// Uncomment during debugging
// console.log('server', servers);
}, {});

let socketUrl =
process.env.NODE_ENV === 'production' ? wssMetricsURL : wssMetricsBaseURL;
process.env.NODE_ENV === "production" ? wssMetricsURL : wssMetricsBaseURL;

const { sendJsonMessage, readyState } = useWebSocket(socketUrl, {
onOpen: () => console.log('WebSocket connection opened.'),
onClose: () => console.log('WebSocket connection closed.'),
onOpen: () => console.log("WebSocket connection opened."),
onClose: () => console.log("WebSocket connection closed."),
shouldReconnect: (closeEvent) => true,
onMessage: (event: WebSocketEventMap['message']) => {
onMessage: (event: WebSocketEventMap["message"]) => {
const newMessage: ServerResponseType = JSON.parse(event.data);
// if (newMessage.Error) return;
setUpdateCount((updateCount) => updateCount + 1);
setServers((prev) => prev.concat(newMessage));
if (jsonMessage) {
setServers({
...servers,
[jsonMessage?.FilterBy as string]: servers[
jsonMessage?.FilterBy as string
]?.concat(newMessage) || [newMessage],
});
}
},
...options,
});

useEffect(() => {
if (jsonMessage) {
sendJsonMessage(jsonMessage);
}
}, [jsonMessage]);

console.log("servers", servers);

const connectionStatus: string = {
[ReadyState.CONNECTING]: 'Connecting',
[ReadyState.OPEN]: 'Open',
[ReadyState.CLOSING]: 'Closing',
[ReadyState.CLOSED]: 'Closed',
[ReadyState.UNINSTANTIATED]: 'Uninstantiated',
[ReadyState.CONNECTING]: "Connecting",
[ReadyState.OPEN]: "Open",
[ReadyState.CLOSING]: "Closing",
[ReadyState.CLOSED]: "Closed",
[ReadyState.UNINSTANTIATED]: "Uninstantiated",
}[readyState];

return {
connectionStatus,
sendJsonMessage,
setJsonMessage,
servers,
serversGroupedByHost,
servicesGroupedByName,
updateCount,
};
}
13 changes: 8 additions & 5 deletions web/src/server/ServerDetail.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import React from "react";
import React, { useEffect } from "react";
import { Container } from "@mui/material";
import { useParams } from "react-router-dom";
import Tabs from "@mui/material/Tabs";
import Tab from "@mui/material/Tab";

import PageHeader from "common/PageHeader";
import LoadingContent from "../common/LoadingContent";
import useSocket from "hooks/useSocket";
import ServerDetailServicesTabPanel from "./ServerDetailServicesTabPanel";
import {
ServerGroupedByNameResponseType,
Expand All @@ -18,16 +17,20 @@ import AppHeader from "AppHeader";
export default function ServerDetail({
servicesGroupedByName,
connectionStatus,
sendJsonMessage,
setJsonMessage,
}: {
servicesGroupedByName: ServerGroupedByNameResponseType;
connectionStatus: string;
sendJsonMessage: (arg0: any) => void;
setJsonMessage: (arg0: any) => void;
}) {
const { host } = useParams<{ host: string }>();
console.log("servicesGroupedByName", servicesGroupedByName);

const [tabIndex, setTabIndex] = React.useState<number>(0);
sendJsonMessage({ FilterBy: host });

useEffect(() => {
setJsonMessage({ FilterBy: host });
}, [host]);

const handleChangeTabIndex = (
event: React.SyntheticEvent,
Expand Down
22 changes: 20 additions & 2 deletions web/src/server/ServerDetailServicesTabPanel.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,15 @@ import ServerDetailServicesTabPanelMemory from "./ServerDetailServicesTabPanelMe
import ServerDetailServicesTabPanelProcess from "./ServerDetailServicesTabPanelProcess";
import ServerDetailServicesTabPanelTCP from "./ServerDetailServicesTabPanelTCP";
import ServerDetailServicesTabPanelUptime from "./ServerDetailServicesTabPanelUptime";
import { DiskData, LoadingAvgData, MemoryData, ProcessData, ServerResponseType, ServerServiceNameType, TCPData } from "./ServerType";
import {
DiskData,
LoadingAvgData,
MemoryData,
ProcessData,
ServerResponseType,
ServerServiceNameType,
TCPData,
} from "./ServerType";

interface ServerDetailServicesTabPanelType {
serverName: ServerServiceNameType;
Expand Down Expand Up @@ -108,5 +116,15 @@ export default function ServerDetailServicesTabPanel(
(service: servicesTabPanelType) => serverName.startsWith(service.title)
);

return <div>{activeServicesTabPanel?.content}</div>;
return (
<div>
{serverData?.Error ? (
<div style={{ textAlign: "center", color: "red" }}>
{serverData?.Message?.Error}
</div>
) : (
activeServicesTabPanel?.content
)}
</div>
);
}
6 changes: 3 additions & 3 deletions web/src/server/ServerList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,16 @@ import AppHeader from "AppHeader";
export default function ServerList({
serversGroupedByHost,
connectionStatus,
sendJsonMessage,
setJsonMessage,
}: {
serversGroupedByHost: ServerGroupedByHostResponseType;
connectionStatus: string;
sendJsonMessage: (arg0: any) => void;
setJsonMessage: (arg0: any) => void;
}) {
const navigate = useNavigate();

useEffect(() => {
sendJsonMessage({ FilterBy: "" });
setJsonMessage({ FilterBy: "" });
}, []);

return (
Expand Down
32 changes: 23 additions & 9 deletions web/src/server/ServerType.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
export type ServerServiceNameType =
| 'disk'
| 'docker'
| 'uptime'
| 'memory'
| 'process'
| 'loadavg'
| 'tcp';
| "disk"
| "docker"
| "uptime"
| "memory"
| "process"
| "loadavg"
| "tcp";

export type ServerResponseMessageData =
| Array<DiskData>
Expand All @@ -19,12 +19,26 @@ export interface ServerResponseType<T = ServerResponseMessageData> {
Error: boolean;
Message: {
Host: string;
Error?: string;
Name: ServerServiceNameType;
Platform: 'Windows' | 'Linux' | 'Darwin' | 'MacOS';
Platform: "Windows" | "Linux" | "Darwin" | "MacOS";
Data: T;
};
}

export interface ServerResponseByHostType<T = ServerResponseMessageData> {
[host: string]: Array<{
Error: boolean;
Message: {
Host: string;
Error?: string;
Name: ServerServiceNameType;
Platform: "Windows" | "Linux" | "Darwin" | "MacOS";
Data: T;
};
}>;
}

export interface MemoryData {
MemFree: number;
MemTotal: number;
Expand Down Expand Up @@ -53,7 +67,7 @@ export interface DockerData {}
export interface UptimeData {}

export interface TCPData {
Ports: Record<number,string>;
Ports: Record<number, string>;
}

export interface ProcessData {
Expand Down

0 comments on commit 61a715d

Please sign in to comment.