refactor create infrastructure

This commit is contained in:
Alex Holliday committed 2024-12-09 13:35:48 +08:00
1 parent dd487c714f
commit 3e21eb0a12
1 file changed
+216 -188
@@ -1,27 +1,66 @@
// React, Redux, Router
import { useTheme } from "@emotion/react";
import { useNavigate, useParams } from "react-router-dom";
import { useEffect } from "react";
import { useState } from "react"; import { useState } from "react";
import { Box, Stack, Typography } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
import { useSelector, useDispatch } from "react-redux"; import { useSelector, useDispatch } from "react-redux";
// Utility and Network
import { infrastructureMonitorValidation } from "../../../Validation/validation"; import { infrastructureMonitorValidation } from "../../../Validation/validation";
import { parseDomainName } from "../../../Utils/monitorUtils";
import { import {
createInfrastructureMonitor, createInfrastructureMonitor,
checkInfrastructureEndpointResolution, checkInfrastructureEndpointResolution,
} from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice"; } from "../../../Features/InfrastructureMonitors/infrastructureMonitorsSlice";
import { useNavigate } from "react-router-dom"; import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
import { useTheme } from "@emotion/react";
import { createToast } from "../../../Utils/toastUtils"; // MUI
import { Box, Stack, Typography, Button, ButtonGroup } from "@mui/material";
import LoadingButton from "@mui/lab/LoadingButton";
//Components
import Breadcrumbs from "../../../Components/Breadcrumbs";
import Link from "../../../Components/Link"; import Link from "../../../Components/Link";
import { ConfigBox } from "../../Monitors/styled"; import { ConfigBox } from "../../Monitors/styled";
import TextInput from "../../../Components/Inputs/TextInput"; import TextInput from "../../../Components/Inputs/TextInput";
import Select from "../../../Components/Inputs/Select"; import { HttpAdornment } from "../../../Components/Inputs/TextInput/Adornments";
import { createToast } from "../../../Utils/toastUtils";
import Checkbox from "../../../Components/Inputs/Checkbox"; import Checkbox from "../../../Components/Inputs/Checkbox";
import Breadcrumbs from "../../../Components/Breadcrumbs"; import Select from "../../../Components/Inputs/Select";
import { buildErrors, hasValidationErrors } from "../../../Validation/error"; import { CustomThreshold } from "./CustomThreshold";
import { capitalizeFirstLetter } from "../../../Utils/stringUtils";
import { CustomThreshold } from "../CreateMonitor/CustomThreshold"; const SELECT_VALUES = [
{ _id: 0.25, name: "15 seconds" },
{ _id: 0.5, name: "30 seconds" },
{ _id: 1, name: "1 minute" },
{ _id: 2, name: "2 minutes" },
{ _id: 5, name: "5 minutes" },
{ _id: 10, name: "10 minutes" },
];
const METRICS = ["cpu", "memory", "disk", "temperature"];
const METRIC_PREFIX = "usage_";
const MS_PER_MINUTE = 60000;
const hasAlertError = (errors) => {
return Object.keys(errors).filter((k) => k.startsWith(METRIC_PREFIX)).length > 0;
};
const getAlertError = (errors) => {
return Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX))
? errors[Object.keys(errors).find((key) => key.startsWith(METRIC_PREFIX))]
: null;
};
const CreateInfrastructureMonitor = () => { const CreateInfrastructureMonitor = () => {
const theme = useTheme();
const { user, authToken } = useSelector((state) => state.auth);
const monitorState = useSelector((state) => state.infrastructureMonitor);
const dispatch = useDispatch();
const navigate = useNavigate();
// State
const [errors, setErrors] = useState({});
const [https, setHttps] = useState(false);
const [infrastructureMonitor, setInfrastructureMonitor] = useState({ const [infrastructureMonitor, setInfrastructureMonitor] = useState({
url: "", url: "",
name: "", name: "",
@@ -38,118 +77,73 @@ const CreateInfrastructureMonitor = () => {
secret: "", secret: "",
}); });
const MS_PER_MINUTE = 60000; // Handlers
const THRESHOLD_FIELD_PREFIX = "usage_"; const handleCreateInfrastructureMonitor = async (event) => {
const HARDWARE_MONITOR_TYPES = ["cpu", "memory", "disk", "temperature"];
const { user, authToken } = useSelector((state) => state.auth);
const monitorState = useSelector((state) => state.infrastructureMonitor);
const dispatch = useDispatch();
const navigate = useNavigate();
const theme = useTheme();
const idMap = {
"notify-email-default": "notification-email",
};
const [errors, setErrors] = useState({});
const alertErrKeyLen = Object.keys(errors).filter((k) =>
k.startsWith(THRESHOLD_FIELD_PREFIX)
).length;
const handleCustomAlertCheckChange = (event) => {
const { value, id } = event.target;
setInfrastructureMonitor((prev) => {
const newState = {
[id]: prev[id] == undefined && value == "on" ? true : !prev[id],
};
return {
...prev,
...newState,
[THRESHOLD_FIELD_PREFIX + id]: newState[id]
? prev[THRESHOLD_FIELD_PREFIX + id]
: "",
};
});
// Remove the error if unchecked
setErrors((prev) => {
return buildErrors(prev, [THRESHOLD_FIELD_PREFIX + id]);
});
};
const handleBlur = (event, appendID) => {
event.preventDefault(); event.preventDefault();
const { value, id } = event.target;
let name = idMap[id] ?? id; // Build the form
if (name === "url" && infrastructureMonitor.name === "") { let form = {
setInfrastructureMonitor((prev) => ({ url: `http${https ? "s" : ""}://` + infrastructureMonitor.url,
...prev, name:
name: parseDomainName(value), infrastructureMonitor.name === ""
})); ? infrastructureMonitor.url
} : infrastructureMonitor.name,
interval: infrastructureMonitor.interval * MS_PER_MINUTE,
cpu: infrastructureMonitor.cpu,
...(infrastructureMonitor.cpu
? { usage_cpu: infrastructureMonitor.usage_cpu }
: {}),
memory: infrastructureMonitor.memory,
...(infrastructureMonitor.memory
? { usage_memory: infrastructureMonitor.usage_memory }
: {}),
disk: infrastructureMonitor.disk,
...(infrastructureMonitor.disk
? { usage_disk: infrastructureMonitor.usage_disk }
: {}),
temperature: infrastructureMonitor.temperature,
...(infrastructureMonitor.temperature
? { usage_temperature: infrastructureMonitor.usage_temperature }
: {}),
secret: infrastructureMonitor.secret,
};
if (id?.startsWith("notify-email-")) return; const { error } = infrastructureMonitorValidation.validate(form, {
const { error } = infrastructureMonitorValidation.validate(
{ [id ?? appendID]: value },
{
abortEarly: false, abortEarly: false,
}
);
setErrors((prev) => {
return buildErrors(prev, id ?? appendID, error);
}); });
};
const handleChange = (event, appendedId) => { if (error) {
event.preventDefault(); const newErrors = {};
const { value, id } = event.target; error.details.forEach((err) => {
let name = appendedId ?? idMap[id] ?? id; newErrors[err.path[0]] = err.message;
if (name.includes("notification-")) {
name = name.replace("notification-", "");
let hasNotif = infrastructureMonitor.notifications.some(
(notification) => notification.type === name
);
setInfrastructureMonitor((prev) => {
const notifs = [...prev.notifications];
if (hasNotif) {
return {
...prev,
notifications: notifs.filter((notif) => notif.type !== name),
};
} else {
return {
...prev,
notifications: [
...notifs,
name === "email"
? { type: name, address: value }
: // TODO - phone number
{ type: name, phone: value },
],
};
}
}); });
} else { setErrors(newErrors);
setInfrastructureMonitor((prev) => ({ createToast({ body: "Please check the form for errors." });
...prev, return;
[name]: value,
}));
} }
};
const generatePayload = (form) => { // Build the thresholds for the form
let thresholds = {}; const {
Object.keys(form) cpu,
.filter((k) => k.startsWith(THRESHOLD_FIELD_PREFIX)) usage_cpu,
.map((k) => { memory,
if (form[k]) thresholds[k] = form[k] / 100; usage_memory,
delete form[k]; disk,
delete form[k.substring(THRESHOLD_FIELD_PREFIX.length)]; usage_disk,
}); temperature,
usage_temperature,
...rest
} = form;
const thresholds = {
...(cpu ? { usage_cpu: usage_cpu / 100 } : {}),
...(memory ? { usage_memory: usage_memory / 100 } : {}),
...(disk ? { usage_disk: usage_disk / 100 } : {}),
...(temperature ? { usage_temperature: usage_temperature / 100 } : {}),
};
form = { form = {
...form, ...rest,
description: form.name, description: form.name,
teamId: user.teamId, teamId: user.teamId,
userId: user._id, userId: user._id,
@@ -157,35 +151,11 @@ const CreateInfrastructureMonitor = () => {
notifications: infrastructureMonitor.notifications, notifications: infrastructureMonitor.notifications,
thresholds, thresholds,
}; };
return form;
};
const handleCreateInfrastructureMonitor = async (event) => {
event.preventDefault();
let form = {
...infrastructureMonitor,
name:
infrastructureMonitor.name === ""
? infrastructureMonitor.url
: infrastructureMonitor.name,
interval: infrastructureMonitor.interval * MS_PER_MINUTE,
};
delete form.notifications; console.log(form);
if (hasValidationErrors(form, infrastructureMonitorValidation, setErrors)) {
return;
} else {
const checkEndpointAction = await dispatch(
checkInfrastructureEndpointResolution({ authToken, monitorURL: form.url })
);
if (checkEndpointAction.meta.requestStatus === "rejected") {
createToast({
body: "The endpoint you entered doesn't resolve. Check the URL again.",
});
setErrors({ url: "The entered URL is not reachable." });
return;
}
const action = await dispatch( const action = await dispatch(
createInfrastructureMonitor({ authToken, monitor: generatePayload(form) }) createInfrastructureMonitor({ authToken, monitor: form })
); );
if (action.meta.requestStatus === "fulfilled") { if (action.meta.requestStatus === "fulfilled") {
createToast({ body: "Infrastructure monitor created successfully!" }); createToast({ body: "Infrastructure monitor created successfully!" });
@@ -193,18 +163,63 @@ const CreateInfrastructureMonitor = () => {
} else { } else {
createToast({ body: "Failed to create monitor." }); createToast({ body: "Failed to create monitor." });
} }
}
}; };
//select values const handleChange = (event, formName) => {
const frequencies = [ const { value } = event.target;
{ _id: 0.25, name: "15 seconds" }, setInfrastructureMonitor({
{ _id: 0.5, name: "30 seconds" }, ...infrastructureMonitor,
{ _id: 1, name: "1 minute" }, [formName]: value,
{ _id: 2, name: "2 minutes" }, });
{ _id: 5, name: "5 minutes" },
{ _id: 10, name: "10 minutes" }, const { error } = infrastructureMonitorValidation.validate(
]; { [formName]: value },
{ abortEarly: false }
);
setErrors((prev) => ({
...prev,
...(error ? { [formName]: error.details[0].message } : { [formName]: undefined }),
}));
};
const handleCheckboxChange = (event, formName) => {
console.log(event.target.checked, formName);
const { checked } = event.target;
setInfrastructureMonitor({
...infrastructureMonitor,
[formName]: checked,
});
};
const handleBlur = (event) => {
console.log("hanldeBlur", event);
};
const handleNotifications = (event, type) => {
const { value } = event.target;
let notifications = [...infrastructureMonitor.notifications];
const notificationExists = notifications.some((notification) => {
if (notification.type === type && notification.address === value) {
return true;
}
return false;
});
if (notificationExists) {
notifications = notifications.filter((notification) => {
if (notification.type === type && notification.address === value) {
return false;
}
return true;
});
} else {
notifications.push({ type, address: value });
}
setInfrastructureMonitor((prev) => ({
...prev,
notifications,
}));
};
return ( return (
<Box className="create-infrastructure-monitor"> <Box className="create-infrastructure-monitor">
@@ -239,16 +254,15 @@ const CreateInfrastructureMonitor = () => {
fontSize="inherit" fontSize="inherit"
fontWeight="inherit" fontWeight="inherit"
> >
infrastructure monitor monitor
</Typography> </Typography>
</Typography> </Typography>
<ConfigBox> <ConfigBox>
<Box>
<Stack gap={theme.spacing(6)}> <Stack gap={theme.spacing(6)}>
<Typography component="h2">General settings</Typography> <Typography component="h2">General settings</Typography>
<Typography component="p"> <Typography component="p">
Here you can select the URL of the host, together with the friendly name Here you can select the URL of the host, together with the friendly name and
and authorization secret to connect to the server agent. authorization secret to connect to the server agent.
</Typography> </Typography>
<Typography component="p"> <Typography component="p">
The server you are monitoring must be running the{" "} The server you are monitoring must be running the{" "}
@@ -259,19 +273,38 @@ const CreateInfrastructureMonitor = () => {
/> />
</Typography> </Typography>
</Stack> </Stack>
</Box>
<Stack gap={theme.spacing(15)}> <Stack gap={theme.spacing(15)}>
<TextInput <TextInput
type="text" type="url"
id="url" id="url"
startAdornment={<HttpAdornment https={https} />}
placeholder={"localhost:59232/api/v1/metrics"}
label="Server URL" label="Server URL"
placeholder="https://" https={https}
value={infrastructureMonitor.url} value={infrastructureMonitor.url}
onBlur={handleBlur} onChange={(event) => handleChange(event, "url")}
onChange={handleChange}
error={errors["url"] ? true : false} error={errors["url"] ? true : false}
helperText={errors["url"]} helperText={errors["url"]}
/> />
<Box>
<Typography component="p">Protocol</Typography>
<ButtonGroup>
<Button
variant="group"
filled={https.toString()}
onClick={() => setHttps(true)}
>
HTTPS
</Button>
<Button
variant="group"
filled={(!https).toString()}
onClick={() => setHttps(false)}
>
HTTP
</Button>
</ButtonGroup>
</Box>
<TextInput <TextInput
type="text" type="text"
id="name" id="name"
@@ -279,8 +312,7 @@ const CreateInfrastructureMonitor = () => {
placeholder="Google" placeholder="Google"
isOptional={true} isOptional={true}
value={infrastructureMonitor.name} value={infrastructureMonitor.name}
onBlur={handleBlur} onChange={(event) => handleChange(event, "name")}
onChange={handleChange}
error={errors["name"]} error={errors["name"]}
/> />
<TextInput <TextInput
@@ -288,8 +320,7 @@ const CreateInfrastructureMonitor = () => {
id="secret" id="secret"
label="Authorization secret" label="Authorization secret"
value={infrastructureMonitor.secret} value={infrastructureMonitor.secret}
onBlur={handleBlur} onChange={(event) => handleChange(event, "secret")}
onChange={handleChange}
error={errors["secret"] ? true : false} error={errors["secret"] ? true : false}
helperText={errors["secret"]} helperText={errors["secret"]}
/> />
@@ -311,12 +342,11 @@ const CreateInfrastructureMonitor = () => {
(notification) => notification.type === "email" (notification) => notification.type === "email"
)} )}
value={user?.email} value={user?.email}
onChange={(e) => handleChange(e)} onChange={(event) => handleNotifications(event, "email")}
onBlur={handleBlur} onBlur={handleBlur}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>
<ConfigBox> <ConfigBox>
<Box> <Box>
<Typography component="h2">Customize alerts</Typography> <Typography component="h2">Customize alerts</Typography>
@@ -326,25 +356,30 @@ const CreateInfrastructureMonitor = () => {
</Typography> </Typography>
</Box> </Box>
<Stack gap={theme.spacing(6)}> <Stack gap={theme.spacing(6)}>
{HARDWARE_MONITOR_TYPES.map((type, idx) => ( {METRICS.map((metric) => {
return (
<CustomThreshold <CustomThreshold
key={idx} key={metric}
checkboxId={type}
checkboxLabel={
type !== "cpu" ? capitalizeFirstLetter(type) : type.toUpperCase()
}
onCheckboxChange={handleCustomAlertCheckChange}
fieldId={THRESHOLD_FIELD_PREFIX + type}
fieldValue={infrastructureMonitor[THRESHOLD_FIELD_PREFIX + type] ?? ""}
onFieldChange={handleChange}
onFieldBlur={handleBlur}
// TODO: need BE, maybe in another PR
alertUnit={type == "temperature" ? "°C" : "%"}
infrastructureMonitor={infrastructureMonitor} infrastructureMonitor={infrastructureMonitor}
errors={errors} errors={errors}
checkboxId={metric}
checkboxLabel={
metric !== "cpu"
? capitalizeFirstLetter(metric)
: metric.toUpperCase()
}
onCheckboxChange={(event) => handleCheckboxChange(event, metric)}
isChecked={infrastructureMonitor[metric]}
fieldId={METRIC_PREFIX + metric}
fieldValue={infrastructureMonitor[METRIC_PREFIX + metric]}
onFieldChange={(event) => handleChange(event, METRIC_PREFIX + metric)}
onFieldBlur={(event) => handleBlur(event, METRIC_PREFIX + metric)}
alertUnit={metric == "temperature" ? "°C" : "%"}
/> />
))} );
{alertErrKeyLen > 0 && ( })}
{/* Error text */}
{hasAlertError(errors) && (
<Typography <Typography
component="span" component="span"
className="input-error" className="input-error"
@@ -354,14 +389,7 @@ const CreateInfrastructureMonitor = () => {
opacity: 0.8, opacity: 0.8,
}} }}
> >
{ {getAlertError(errors)}
errors[
THRESHOLD_FIELD_PREFIX +
HARDWARE_MONITOR_TYPES.filter(
(type) => errors[THRESHOLD_FIELD_PREFIX + type]
)[0]
]
}
</Typography> </Typography>
)} )}
</Stack> </Stack>
@@ -377,7 +405,7 @@ const CreateInfrastructureMonitor = () => {
value={infrastructureMonitor.interval || 15} value={infrastructureMonitor.interval || 15}
onChange={(e) => handleChange(e, "interval")} onChange={(e) => handleChange(e, "interval")}
onBlur={(e) => handleBlur(e, "interval")} onBlur={(e) => handleBlur(e, "interval")}
items={frequencies} items={SELECT_VALUES}
/> />
</Stack> </Stack>
</ConfigBox> </ConfigBox>