cleaned up code and refactored code to not have a default sort on load

This commit is contained in:
Alvaro Torres committed 2024-08-15 09:35:19 -05:00
commit 0e8691b580
15 files changed
+232 -198

No files matched your search

+9 -15
View File
@@ -18,7 +18,7 @@
"@mui/x-data-grid": "7.3.2", "@mui/x-data-grid": "7.3.2",
"@mui/x-date-pickers": "7.3.2", "@mui/x-date-pickers": "7.3.2",
"@reduxjs/toolkit": "2.2.5", "@reduxjs/toolkit": "2.2.5",
"axios": "^1.3.1", "axios": "1.7.4",
"chart.js": "^4.4.3", "chart.js": "^4.4.3",
"dayjs": "1.11.11", "dayjs": "1.11.11",
"joi": "17.13.1", "joi": "17.13.1",
@@ -29,7 +29,7 @@
"react-router": "^6.23.0", "react-router": "^6.23.0",
"react-router-dom": "^6.23.1", "react-router-dom": "^6.23.1",
"react-toastify": "^10.0.5", "react-toastify": "^10.0.5",
"recharts": "2.12.7", "recharts": "2.13.0-alpha.4",
"redux-persist": "6.0.0", "redux-persist": "6.0.0",
"vite-plugin-svgr": "^4.2.0" "vite-plugin-svgr": "^4.2.0"
}, },
@@ -2655,9 +2655,9 @@
} }
}, },
"node_modules/axios": { "node_modules/axios": {
"version": "1.3.1", "version": "1.7.2",
"resolved": "https://registry.npmjs.org/axios/-/axios-1.3.1.tgz", "resolved": "https://registry.npmjs.org/axios/-/axios-1.7.2.tgz",
"integrity": "sha512-78pWJsQTceInlyaeBQeYZ/QgZeWS8hGeKiIJiDKQe3hEyBb7sEMq0K4gjx+Va6WHTYO4zI/RRl8qGRzn0YMadA==", "integrity": "sha512-2A8QhOMrbomlDuiLeK9XibIBzuHeRcqqNOHp0Cyp5EoJ1IFDh+XZH3A6BkXtv0K4gFGCI0Y4BM7B1wOEi0Rmgw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"follow-redirects": "^1.15.0", "follow-redirects": "^1.15.0",
@@ -5509,15 +5509,15 @@
} }
}, },
"node_modules/recharts": { "node_modules/recharts": {
"version": "2.12.7", "version": "2.13.0-alpha.4",
"resolved": "https://registry.npmjs.org/recharts/-/recharts-2.12.7.tgz", "resolved": "https://registry.npmjs.org/recharts/-/recharts-2.13.0-alpha.4.tgz",
"integrity": "sha512-hlLJMhPQfv4/3NBSAyq3gzGg4h2v69RJh6KU7b3pXYNNAELs9kEoXOjbkxdXpALqKBoVmVptGfLpxdaVYqjmXQ==", "integrity": "sha512-K9naL6F7pEcDYJE6yFQASSCQecSLPP0JagnvQ9hPtA/aHgsxsnIOjouLP5yrFZehxzfCkV5TEORr7/uNtSr7Qw==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"clsx": "^2.0.0", "clsx": "^2.0.0",
"eventemitter3": "^4.0.1", "eventemitter3": "^4.0.1",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"react-is": "^16.10.2", "react-is": "^18.3.1",
"react-smooth": "^4.0.0", "react-smooth": "^4.0.0",
"recharts-scale": "^0.4.4", "recharts-scale": "^0.4.4",
"tiny-invariant": "^1.3.1", "tiny-invariant": "^1.3.1",
@@ -5540,12 +5540,6 @@
"decimal.js-light": "^2.4.1" "decimal.js-light": "^2.4.1"
} }
}, },
"node_modules/recharts/node_modules/react-is": {
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"license": "MIT"
},
"node_modules/redux": { "node_modules/redux": {
"version": "5.0.1", "version": "5.0.1",
"resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz",
+2 -1
View File
@@ -21,6 +21,7 @@
"@mui/x-date-pickers": "7.3.2", "@mui/x-date-pickers": "7.3.2",
"@reduxjs/toolkit": "2.2.5", "@reduxjs/toolkit": "2.2.5",
"axios": "^1.3.1", "axios": "^1.3.1",
"axios": "1.7.4",
"chart.js": "^4.4.3", "chart.js": "^4.4.3",
"dayjs": "1.11.11", "dayjs": "1.11.11",
"joi": "17.13.1", "joi": "17.13.1",
@@ -31,7 +32,7 @@
"react-router": "^6.23.0", "react-router": "^6.23.0",
"react-router-dom": "^6.23.1", "react-router-dom": "^6.23.1",
"react-toastify": "^10.0.5", "react-toastify": "^10.0.5",
"recharts": "2.12.7", "recharts": "2.13.0-alpha.4",
"redux-persist": "6.0.0", "redux-persist": "6.0.0",
"vite-plugin-svgr": "^4.2.0" "vite-plugin-svgr": "^4.2.0"
}, },
+1 -1
View File
@@ -72,7 +72,7 @@
} }
.MuiPaper-root + .MuiPagination-root { .MuiPaper-root + .MuiPagination-root {
margin-top: 35px; margin-top: 24px;
border: solid 1px var(--env-var-color-16); border: solid 1px var(--env-var-color-16);
border-radius: var(--env-var-radius-1); border-radius: var(--env-var-radius-1);
padding: var(--env-var-spacing-1-plus) var(--env-var-spacing-2); padding: var(--env-var-spacing-1-plus) var(--env-var-spacing-2);
@@ -0,0 +1,50 @@
import { BarChart, Bar, Cell, ReferenceLine, Label } from "recharts";
import PropTypes from "prop-types";
const MonitorDetails60MinChart = ({ data }) => {
const labelStyle = {
fontSize: "10px",
fill: "#475467",
};
const color = {
true: "var(--env-var-color-23)",
false: "var(--env-var-color-24)",
undefined: "var(--env-var-color-33)",
};
return (
<BarChart
width={data.length * 10 + 30}
height={35}
data={data}
margin={{ top: 14, left: 15, right: 15, bottom: 2 }}
style={{ alignSelf: "baseline" }}
>
<Bar dataKey="value" barSize={10}>
{data.map((check, index) => (
<Cell key={`cell-${index}`} fill={color[check.status]} />
))}
</Bar>
<ReferenceLine x={0} stroke="black" strokeDasharray="3 3">
<Label value="60 mins" position="top" style={labelStyle} />
</ReferenceLine>
<ReferenceLine
x={Math.floor(data.length * (2 / 3))}
stroke="black"
strokeDasharray="3 3"
>
<Label value="20 mins" position="top" style={labelStyle} />
</ReferenceLine>
<ReferenceLine x={data.length - 1} stroke="black" strokeDasharray="3 3">
<Label value="now" position="top" style={labelStyle} />
</ReferenceLine>
</BarChart>
);
};
MonitorDetails60MinChart.propTypes = {
data: PropTypes.array.isRequired,
};
export default MonitorDetails60MinChart;
@@ -28,15 +28,6 @@ const CustomToolTip = ({ active, payload, label }) => {
}; };
const MonitorDetailsAreaChart = ({ checks }) => { const MonitorDetailsAreaChart = ({ checks }) => {
// SQUASH ERROR, NOT PERMANENT SOLUTION
const error = console.error;
console.error = (...args) => {
if (/defaultProps/.test(args[0])) return;
error(...args);
};
// END SQUASH ERROR, NOT PERMANENT SOLUTION
const formatDate = (timestamp) => { const formatDate = (timestamp) => {
const date = new Date(timestamp); const date = new Date(timestamp);
return date.toLocaleTimeString("en-US", { return date.toLocaleTimeString("en-US", {
+12 -8
View File
@@ -3,12 +3,10 @@
color: var(--env-var-color-1); color: var(--env-var-color-1);
font-weight: 600; font-weight: 600;
} }
.monitor-details h2.MuiTypography-root, .monitor-details h2.MuiTypography-root {
.monitor-details h6.MuiTypography-root {
font-size: var(--env-var-font-size-large); font-size: var(--env-var-font-size-large);
} }
.monitor-details h2.MuiTypography-root, .monitor-details h2.MuiTypography-root{
.monitor-details h4.MuiTypography-root {
font-weight: 600; font-weight: 600;
} }
.monitor-details h2.MuiTypography-root, .monitor-details h2.MuiTypography-root,
@@ -35,15 +33,21 @@
} }
.monitor-details .stat-box { .monitor-details .stat-box {
flex: 1; flex: 1 20%;
min-width: 100px; min-width: 100px;
border: solid 1px; border: solid 1px;
border-radius: var(--env-var-radius-1); border-radius: var(--env-var-radius-1);
padding: var(--env-var-spacing-1) 18px; padding: var(--env-var-spacing-1) 16px;
background-color: var(--env-var-color-8); background-color: var(--env-var-color-8);
} }
.monitor-details .stat-box h6.MuiTypography-root { .monitor-details h6.MuiTypography-root {
margin-bottom: var(--env-var-spacing-1); font-size: var(--env-var-font-size-medium-plus);
}
.monitor-details h6.MuiTypography-root span.MuiTypography-root {
font-style: italic;
font-size: var(--env-var-font-size-medium);
color: var(--env-var-color-5);
opacity: 0.7;
} }
.monitor-details button.MuiButtonBase-root, .monitor-details button.MuiButtonBase-root,
.monitor-details .stat-box { .monitor-details .stat-box {
+52 -24
View File
@@ -17,20 +17,23 @@ import {
formatDurationRounded, formatDurationRounded,
} from "../../../Utils/timeUtils"; } from "../../../Utils/timeUtils";
import "./index.css"; import "./index.css";
import MonitorDetails60MinChart from "../../../Components/Charts/MonitorDetails60MinChart";
const StatBox = ({ title, value }) => { const StatBox = ({ title, value }) => {
return ( return (
<Box className="stat-box"> <Box className="stat-box">
<Typography variant="h6" sx={{ fontWeight: 400 }}> <Typography variant="h6" mb={1} fontWeight={500}>
{title} {title}
</Typography> </Typography>
<Typography variant="h4">{value}</Typography> <Typography variant="h4" fontWeight={500}>
{value}
</Typography>
</Box> </Box>
); );
}; };
StatBox.propTypes = { StatBox.propTypes = {
title: PropTypes.string, title: PropTypes.oneOfType([PropTypes.string, PropTypes.element]),
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}; };
@@ -162,12 +165,12 @@ const DetailsPage = () => {
<> <>
<Button <Button
level="tertiary" level="tertiary"
label="Back to Monitors" label="Back"
animate="slideLeft" animate="slideLeft"
img={<WestRoundedIcon />} img={<WestRoundedIcon />}
onClick={() => navigate("/monitors")} onClick={() => navigate("/monitors")}
sx={{ sx={{
backgroundColor: "#f4f4f4", backgroundColor: theme.palette.otherColors.fillGray,
px: theme.gap.ml, px: theme.gap.ml,
"& svg.MuiSvgIcon-root": { "& svg.MuiSvgIcon-root": {
mr: theme.gap.small, mr: theme.gap.small,
@@ -176,12 +179,23 @@ const DetailsPage = () => {
}} }}
/> />
<Stack gap={theme.gap.xl} mt={theme.gap.medium}> <Stack gap={theme.gap.xl} mt={theme.gap.medium}>
<Stack direction="row" gap={theme.gap.small} mt={theme.gap.small}> <Stack
direction="row"
gap={theme.gap.small}
mt={theme.gap.small}
alignItems="baseline"
>
{monitor?.status ? <GreenCheck /> : <RedCheck />} {monitor?.status ? <GreenCheck /> : <RedCheck />}
<Box> <Box>
<Typography component="h1" sx={{ lineHeight: 1 }}> <Stack direction="row">
{monitor.url?.replace(/^https?:\/\//, "") || "..."} <Typography
</Typography> component="h1"
sx={{ lineHeight: 1, alignSelf: "flex-end" }}
>
{monitor.url?.replace(/^https?:\/\//, "") || "..."}
</Typography>
<MonitorDetails60MinChart data={monitor.statusBar} />
</Stack>
<Typography mt={theme.gap.small}> <Typography mt={theme.gap.small}>
<Typography <Typography
component="span" component="span"
@@ -194,8 +208,6 @@ const DetailsPage = () => {
Your site is {monitor?.status ? "up" : "down"}. Your site is {monitor?.status ? "up" : "down"}.
</Typography>{" "} </Typography>{" "}
Checking every {formatDurationRounded(monitor?.interval)}. Checking every {formatDurationRounded(monitor?.interval)}.
Last time checked{" "}
{formatDurationRounded(monitor?.lastChecked)} ago.
</Typography> </Typography>
</Box> </Box>
<Button <Button
@@ -226,41 +238,49 @@ const DetailsPage = () => {
direction="row" direction="row"
justifyContent="space-between" justifyContent="space-between"
gap={theme.gap.large} gap={theme.gap.large}
flexWrap="wrap"
> >
<StatBox <StatBox
title="Currently up for" title="Currently up for"
value={formatDuration(monitor?.uptimeDuration)} value={formatDuration(monitor?.uptimeDuration)}
/> />
<StatBox <StatBox
title="Last checked" title="Last check"
value={`${formatDuration(monitor?.lastChecked)} ago`} value={`${formatDurationRounded(monitor?.lastChecked)} ago`}
/> />
<StatBox title="Incidents" value={monitor?.incidents} /> <StatBox title="Incidents" value={monitor?.incidents} />
<StatBox title="Certificate Expiry" value={certificateExpiry} /> <StatBox title="Certificate Expiry" value={certificateExpiry} />
</Stack>
<Stack
direction="row"
justifyContent="space-between"
gap={theme.gap.large}
>
<StatBox <StatBox
title="Latest response time" title="Latest response time"
value={monitor?.latestResponseTime} value={monitor?.latestResponseTime}
/> />
<StatBox <StatBox
title="Average Repsonse Time (24 hours)" title={
<>
Avg. Response Time{" "}
<Typography component="span">(24-hr)</Typography>
</>
}
value={parseFloat(monitor?.avgResponseTime24hours) value={parseFloat(monitor?.avgResponseTime24hours)
.toFixed(2) .toFixed(2)
.replace(/\.?0+$/, "")} .replace(/\.?0+$/, "")}
/> />
<StatBox <StatBox
title="Uptime (24 hours)" title={
<>
Uptime <Typography component="span">(24-hr)</Typography>
</>
}
value={`${parseFloat(monitor?.uptime24Hours) value={`${parseFloat(monitor?.uptime24Hours)
.toFixed(2) .toFixed(2)
.replace(/\.?0+$/, "")}%`} .replace(/\.?0+$/, "")}%`}
/> />
<StatBox <StatBox
title="Uptime(30 days)" title={
<>
Uptime <Typography component="span">(30-day)</Typography>
</>
}
value={`${parseFloat(monitor?.uptime30Days) value={`${parseFloat(monitor?.uptime30Days)
.toFixed(2) .toFixed(2)
.replace(/\.?0+$/, "")}%`} .replace(/\.?0+$/, "")}%`}
@@ -272,7 +292,7 @@ const DetailsPage = () => {
justifyContent="space-between" justifyContent="space-between"
mb={theme.gap.ml} mb={theme.gap.ml}
> >
<Typography component="h2" mb={theme.gap.small}> <Typography component="h2" alignSelf="flex-end">
Response Times Response Times
</Typography> </Typography>
<ButtonGroup> <ButtonGroup>
@@ -308,7 +328,15 @@ const DetailsPage = () => {
/> />
</ButtonGroup> </ButtonGroup>
</Stack> </Stack>
<Box sx={{ height: "200px" }}> <Box
p={theme.gap.mlplus}
pb={theme.gap.xs}
backgroundColor={theme.palette.otherColors.white}
border={1}
borderColor={theme.palette.otherColors.graishWhite}
borderRadius={`${theme.shape.borderRadius}px`}
sx={{ height: "250px" }}
>
<MonitorDetailsAreaChart <MonitorDetailsAreaChart
checks={[...monitor.checks].reverse()} checks={[...monitor.checks].reverse()}
/> />
+28 -5
View File
@@ -9,6 +9,7 @@ import { useNavigate } from "react-router-dom";
import Button from "../../Components/Button"; import Button from "../../Components/Button";
import ServerStatus from "../../Components/Charts/Servers/ServerStatus"; import ServerStatus from "../../Components/Charts/Servers/ServerStatus";
import { useTheme } from "@emotion/react"; import { useTheme } from "@emotion/react";
import ArrowUpwardRoundedIcon from "@mui/icons-material/ArrowUpwardRounded";
import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded"; import ArrowDownwardRoundedIcon from "@mui/icons-material/ArrowDownwardRounded";
import OpenInNewPage from "../../assets/icons/open-in-new-page.svg?react"; import OpenInNewPage from "../../assets/icons/open-in-new-page.svg?react";
import Settings from "../../assets/icons/settings-bold.svg?react"; import Settings from "../../assets/icons/settings-bold.svg?react";
@@ -152,17 +153,38 @@ const Monitors = () => {
const down = monitorState.monitors.length - up; const down = monitorState.monitors.length - up;
// State variable for sorting -> default of 1 for ascending
const [sortOrder, setSortOrder] = useState(1);
// State variable for updating sorting of default monitors
const [sortedMonitors, setSortedMonitors] = useState(monitorState.monitors);
// Bool for sorting arrow
const [isSorted, setIsSorted] = useState(false);
// Function to handle sorting on click of status text
const handleSort = () => {
setSortOrder(prevOrder => prevOrder * -1);
// Sort existing monitors with start of ascending order
const monitors = [...monitorState.monitors].sort(a => {
return a.status ? -1 * sortOrder : 1 * sortOrder;
});
// Update state of monitors
setSortedMonitors(monitors);
// Trigger arrow visibility and direction
setIsSorted(true);
};
const data = { const data = {
cols: [ cols: [
{ id: 1, name: "Host" }, { id: 1, name: "Host" },
{ {
id: 2, id: 2,
name: ( name: (
<Box width="max-content"> <Box width="max-content" onClick={handleSort} style={{ cursor: "pointer" }}>
Status Status
<span> {isSorted ? <span>{sortOrder === -1 ? <ArrowUpwardRoundedIcon /> : <ArrowDownwardRoundedIcon />}</span> : null}
<ArrowDownwardRoundedIcon />
</span>
</Box> </Box>
), ),
}, },
@@ -173,7 +195,8 @@ const Monitors = () => {
rows: [], rows: [],
}; };
data.rows = monitorState.monitors.map((monitor, idx) => { // Render out sorted monitors/default monitors
data.rows = sortedMonitors.map((monitor, idx) => {
const params = { const params = {
url: monitor.url, url: monitor.url,
title: monitor.name, title: monitor.name,
+2 -2
View File
@@ -299,7 +299,7 @@ const PageSpeedDetails = () => {
const [expand, setExpand] = useState(false); const [expand, setExpand] = useState(false);
let loading = Object.keys(monitor).length === 0; let loading = Object.keys(monitor).length === 0;
const data = monitor?.checks ? [...monitor.checks].reverse() : [];
return ( return (
<Stack className="page-speed-details" gap={theme.gap.large}> <Stack className="page-speed-details" gap={theme.gap.large}>
{loading ? ( {loading ? (
@@ -406,7 +406,7 @@ const PageSpeedDetails = () => {
</Stack> </Stack>
<Typography component="h2">Score history</Typography> <Typography component="h2">Score history</Typography>
<Box height="300px"> <Box height="300px">
<PageSpeedLineChart pageSpeedChecks={monitor?.checks?.reverse()} /> <PageSpeedLineChart pageSpeedChecks={data} />
</Box> </Box>
<Typography component="h2">Performance report</Typography> <Typography component="h2">Performance report</Typography>
<Stack direction="row" alignItems="center" overflow="hidden" flex={1}> <Stack direction="row" alignItems="center" overflow="hidden" flex={1}>
+1
View File
@@ -58,6 +58,7 @@
--env-var-color-30: #fcfcfd; --env-var-color-30: #fcfcfd;
--env-var-color-31: #1a1919; --env-var-color-31: #1a1919;
--env-var-color-32: #f5f5f5; --env-var-color-32: #f5f5f5;
--env-var-color-33: rgba(83, 83, 83, 0.1);
--env-var-radius-1: 4px; --env-var-radius-1: 4px;
--env-var-radius-2: 8px; --env-var-radius-2: 8px;
+18 -65
View File
@@ -126,10 +126,22 @@ const getIncidents = (checks) => {
* @param {Array} checks Array of check objects. * @param {Array} checks Array of check objects.
* @returns {Array<Boolean>} Array of booleans representing up/down. * @returns {Array<Boolean>} Array of booleans representing up/down.
*/ */
const getStatusBarValues = (checks) => { const getStatusBarValues = (monitor, checks) => {
return checks.map((check) => { const checksIn60Mins = Math.floor((60 * 60 * 1000) / monitor.interval);
return check.status; const noBlankChecks = checksIn60Mins - checks.length;
const statusBarValues = checks.map((check) => {
return {
status: check.status,
responseTime: check.responseTime,
value: 75,
};
}); });
for (let i = 0; i < noBlankChecks; i++) {
statusBarValues.push({ status: undefined, responseTime: 0, value: 75 });
}
return statusBarValues.reverse();
}; };
/** /**
* Get stats by monitor ID * Get stats by monitor ID
@@ -205,7 +217,7 @@ const getMonitorStatsById = async (req) => {
getAverageResponseTime24Hours(checks24Hours); getAverageResponseTime24Hours(checks24Hours);
monitorStats.uptime24Hours = getUptimePercentage(checks24Hours); monitorStats.uptime24Hours = getUptimePercentage(checks24Hours);
monitorStats.uptime30Days = getUptimePercentage(checks30Days); monitorStats.uptime30Days = getUptimePercentage(checks30Days);
monitorStats.statusBar = getStatusBarValues(checks60Mins); monitorStats.statusBar = getStatusBarValues(monitor, checks60Mins);
} }
//Get checks for dateRange //Get checks for dateRange
@@ -263,69 +275,10 @@ const getMonitorStatsById = async (req) => {
* @returns {Promise<Monitor>} * @returns {Promise<Monitor>}
* @throws {Error} * @throws {Error}
*/ */
const getMonitorById = async (req, res) => { const getMonitorById = async (monitorId) => {
try { try {
const { monitorId } = req.params;
let { status, limit, sortOrder, filter, numToDisplay, normalize } =
req.query;
const filterLookup = {
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
};
// This effectively removes limit, returning all checks
if (limit === undefined) limit = 0;
// Default sort order is newest -> oldest
if (sortOrder === "asc") {
sortOrder = 1;
} else if (sortOrder === "desc") {
sortOrder = -1;
} else sortOrder = -1;
const monitor = await Monitor.findById(monitorId); const monitor = await Monitor.findById(monitorId);
return monitor;
const checksQuery = { monitorId: monitor._id };
if (status !== undefined) {
checksQuery.status = status;
}
// Filter checks by "day", "week", or "month"
if (filter !== undefined) {
checksQuery.createdAt = { $gte: filterLookup[filter] };
}
// Determine model type
let model =
monitor.type === "http" || monitor.type === "ping"
? Check
: PageSpeedCheck;
let checks = await model
.find(checksQuery)
.sort({
createdAt: sortOrder,
})
.limit(limit);
// If more than numToDisplay checks, pick every nth check
if (numToDisplay !== undefined && checks && checks.length > numToDisplay) {
const n = Math.ceil(checks.length / numToDisplay);
checks = checks.filter(
(_, index) => index % n === 0 || index === checks.length - 1
);
}
// Normalize checks if requested
if (normalize !== undefined) {
checks = NormalizeData(checks, 1, 100);
}
const notifications = await Notification.find({ monitorId: monitor._id });
const monitorWithChecks = { ...monitor.toObject(), checks, notifications };
return monitorWithChecks;
} catch (error) { } catch (error) {
throw error; throw error;
} }
+3 -1
View File
@@ -16,6 +16,7 @@ const maintenanceWindowRouter = require("./routes/maintenanceWindowRoute");
const { connectDbAndRunServer } = require("./configs/db"); const { connectDbAndRunServer } = require("./configs/db");
const queueRouter = require("./routes/queueRoute"); const queueRouter = require("./routes/queueRoute");
const JobQueue = require("./service/jobQueue"); const JobQueue = require("./service/jobQueue");
const NetworkService = require("./service/networkService");
const EmailService = require("./service/emailService"); const EmailService = require("./service/emailService");
const PageSpeedService = require("./service/pageSpeedService"); const PageSpeedService = require("./service/pageSpeedService");
@@ -114,8 +115,9 @@ const startApp = async () => {
// Create services // Create services
await connectDbAndRunServer(app, db); await connectDbAndRunServer(app, db);
const jobQueue = await JobQueue.createJobQueue(db);
const emailService = new EmailService(); const emailService = new EmailService();
const networkService = new NetworkService(db, emailService);
const jobQueue = await JobQueue.createJobQueue(db, networkService);
const pageSpeedService = new PageSpeedService(); const pageSpeedService = new PageSpeedService();
const cleanup = async () => { const cleanup = async () => {
-57
View File
@@ -69,61 +69,4 @@ const CheckSchema = mongoose.Schema(
} }
); );
/**
* Pre-save middleware to handle status change notifications.
*
* This middleware checks if the status of the monitor associated
* with the check has changed and sends notifications if necessary.
*/
CheckSchema.pre("save", async function (next) {
try {
const monitor = await mongoose.model("Monitor").findById(this.monitorId);
if (monitor) {
const notifications = await Notification.find({
monitorId: this.monitorId,
});
// Check if there are any notifications
// Only send email if monitor status has changed
if (monitor.status !== this.status) {
const emailService = new EmailService();
let template = "";
let status = "";
if (monitor.status === true && this.status === false) {
template = "serverIsDownTemplate";
status = "down";
}
if (monitor.status === false && this.status === true) {
// Notify users that the monitor is up
template = "serverIsUpTemplate";
status = "up";
}
for (const notification of notifications) {
if (notification.type === "email") {
await emailService.buildAndSendEmail(
template,
{ monitorName: monitor.name, monitorUrl: monitor.url },
notification.address,
`Monitor ${monitor.name} is ${status}`
);
}
}
// Update monitor status
monitor.status = this.status;
await monitor.save();
}
}
} catch (error) {
console.log(error);
} finally {
next();
}
});
module.exports = mongoose.model("Check", CheckSchema); module.exports = mongoose.model("Check", CheckSchema);
+3 -3
View File
@@ -16,7 +16,7 @@ class JobQueue {
* @constructor * @constructor
* @throws {Error} * @throws {Error}
*/ */
constructor() { constructor(networkService) {
this.queue = new Queue(QUEUE_NAME, { this.queue = new Queue(QUEUE_NAME, {
connection, connection,
}); });
@@ -32,11 +32,11 @@ class JobQueue {
* @returns {Promise<JobQueue>} - Returns a new JobQueue * @returns {Promise<JobQueue>} - Returns a new JobQueue
* *
*/ */
static async createJobQueue(db) { static async createJobQueue(db, networkService) {
const queue = new JobQueue(); const queue = new JobQueue();
try { try {
queue.db = db; queue.db = db;
queue.networkService = new NetworkService(db); queue.networkService = networkService;
const monitors = await db.getAllMonitors(); const monitors = await db.getAllMonitors();
for (const monitor of monitors) { for (const monitor of monitors) {
await queue.addJob(monitor.id, monitor); await queue.addJob(monitor.id, monitor);
+51 -7
View File
@@ -3,8 +3,9 @@ const ping = require("ping");
const logger = require("../utils/logger"); const logger = require("../utils/logger");
class NetworkService { class NetworkService {
constructor(db) { constructor(db, emailService) {
this.db = db; this.db = db;
this.emailService = emailService;
this.TYPE_PING = "ping"; this.TYPE_PING = "ping";
this.TYPE_HTTP = "http"; this.TYPE_HTTP = "http";
this.TYPE_PAGESPEED = "pagespeed"; this.TYPE_PAGESPEED = "pagespeed";
@@ -12,6 +13,33 @@ class NetworkService {
this.NETWORK_ERROR = 5000; this.NETWORK_ERROR = 5000;
} }
async handleNotification(job, isAlive) {
const { _id } = job.data;
const monitor = await this.db.getMonitorById(_id);
// If monitor status changes, update monitor status and send notification
if (monitor.status !== isAlive) {
monitor.status = !monitor.status;
await monitor.save();
let template =
isAlive === true ? "serverIsUpTemplate" : "serverIsDownTemplate";
let status = isAlive === true ? "up" : "down";
const notifications = await this.db.getNotificationsByMonitorId(_id);
for (const notification of notifications) {
if (notification.type === "email") {
await this.emailService.buildAndSendEmail(
template,
{ monitorName: monitor.name, monitorUrl: monitor.url },
notification.address,
`Monitor ${monitor.name} is ${status}`
);
}
}
}
}
/** /**
* Measures the response time of an asynchronous operation. * Measures the response time of an asynchronous operation.
* @param {Function} operation - An asynchronous operation to measure. * @param {Function} operation - An asynchronous operation to measure.
@@ -42,10 +70,12 @@ class NetworkService {
return response; return response;
}; };
let isAlive;
try { try {
const { responseTime, response } = const { responseTime, response } =
await this.measureResponseTime(operation); await this.measureResponseTime(operation);
const isAlive = response.alive; isAlive = response.alive;
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
@@ -54,12 +84,15 @@ class NetworkService {
}; };
return await this.logAndStoreCheck(checkData, this.db.createCheck); return await this.logAndStoreCheck(checkData, this.db.createCheck);
} catch (error) { } catch (error) {
isAlive = false;
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
status: false, status: isAlive,
responseTime: error.responseTime, responseTime: error.responseTime,
}; };
return await this.logAndStoreCheck(checkData, this.db.createCheck); return await this.logAndStoreCheck(checkData, this.db.createCheck);
} finally {
this.handleNotification(job, isAlive);
} }
} }
@@ -75,13 +108,15 @@ class NetworkService {
return response; return response;
}; };
let isAlive;
// attempt connection // attempt connection
try { try {
const { responseTime, response } = const { responseTime, response } =
await this.measureResponseTime(operation); await this.measureResponseTime(operation);
// check if response is in the 200 range, if so, service is up // check if response is in the 200 range, if so, service is up
const isAlive = response.status >= 200 && response.status < 300; isAlive = response.status >= 200 && response.status < 300;
//Create a check with relevant data //Create a check with relevant data
const checkData = { const checkData = {
@@ -92,9 +127,10 @@ class NetworkService {
}; };
return await this.logAndStoreCheck(checkData, this.db.createCheck); return await this.logAndStoreCheck(checkData, this.db.createCheck);
} catch (error) { } catch (error) {
isAlive = false;
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
status: false, status: isAlive,
responseTime: error.responseTime, responseTime: error.responseTime,
}; };
// The server returned a response // The server returned a response
@@ -104,6 +140,8 @@ class NetworkService {
checkData.statusCode = this.NETWORK_ERROR; checkData.statusCode = this.NETWORK_ERROR;
} }
return await this.logAndStoreCheck(checkData, this.db.createCheck); return await this.logAndStoreCheck(checkData, this.db.createCheck);
} finally {
this.handleNotification(job, isAlive);
} }
} }
@@ -122,6 +160,8 @@ class NetworkService {
* @throws {Error} Throws an error if there is an issue with fetching or processing the PageSpeed insights. * @throws {Error} Throws an error if there is an issue with fetching or processing the PageSpeed insights.
*/ */
async handlePagespeed(job) { async handlePagespeed(job) {
let isAlive;
try { try {
const url = job.data.url; const url = job.data.url;
const response = await axios.get( const response = await axios.get(
@@ -145,9 +185,10 @@ class NetworkService {
// Total Blocking Time 30% // Total Blocking Time 30%
// Cumulative Layout Shift 25% // Cumulative Layout Shift 25%
isAlive = true;
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
status: true, status: isAlive,
accessibility: (categories.accessibility?.score || 0) * 100, accessibility: (categories.accessibility?.score || 0) * 100,
bestPractices: (categories["best-practices"]?.score || 0) * 100, bestPractices: (categories["best-practices"]?.score || 0) * 100,
seo: (categories.seo?.score || 0) * 100, seo: (categories.seo?.score || 0) * 100,
@@ -163,15 +204,18 @@ class NetworkService {
this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck); this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck);
} catch (error) { } catch (error) {
isAlive = false;
const checkData = { const checkData = {
monitorId: job.data._id, monitorId: job.data._id,
status: false, status: isAlive,
accessibility: 0, accessibility: 0,
bestPractices: 0, bestPractices: 0,
seo: 0, seo: 0,
performance: 0, performance: 0,
}; };
this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck); this.logAndStoreCheck(checkData, this.db.createPageSpeedCheck);
} finally {
this.handleNotification(job, isAlive);
} }
} }