Merge pull request #571 from bluewave-labs/feat/be/get-monitor-by-id-refactor

Feat/be/get monitor by id refactor
This commit is contained in:
Alexander Holliday authored and GitHub committed 2024-08-08 14:22:18 -07:00
commit b9b1d4be05
8 files changed
+125 -51

No files matched your search

@@ -1,46 +0,0 @@
const calculatePercentile = (arr, percentile) => {
const sorted = arr.slice().sort((a, b) => a.responseTime - b.responseTime);
const index = (percentile / 100) * (sorted.length - 1);
const lower = Math.floor(index);
const upper = lower + 1;
const weight = index % 1;
if (upper >= sorted.length) return sorted[lower].responseTime;
return (
sorted[lower].responseTime * (1 - weight) +
sorted[upper].responseTime * weight
);
};
export const NormalizeData = (checks, rangeMin, rangeMax) => {
if (checks.length > 1) {
// Get the 5th and 95th percentile
const min = calculatePercentile(checks, 0);
const max = calculatePercentile(checks, 95);
const normalizedChecks = checks.map((check) => {
const originalResponseTime = check.responseTime;
// Normalize the response time between 1 and 100
let normalizedResponseTime =
rangeMin +
((check.responseTime - min) * (rangeMax - rangeMin)) / (max - min);
// Put a floor on the response times so we don't have extreme outliers
// Better visuals
normalizedResponseTime = Math.max(
rangeMin,
Math.min(rangeMax, normalizedResponseTime)
);
return {
...check,
responseTime: normalizedResponseTime,
originalResponseTime: originalResponseTime,
};
});
return normalizedChecks;
} else {
return checks.map((check) => {
return { ...check, originalResponseTime: check.responseTime };
});
}
};
@@ -1,6 +1,5 @@
import PropTypes from "prop-types";
import { AreaChart, Area, XAxis, Tooltip, ResponsiveContainer } from "recharts";
import { NormalizeData } from "../ChartUtils";
import "./index.css";
const CustomToolTip = ({ active, payload, label }) => {
@@ -28,7 +27,7 @@ const CustomToolTip = ({ active, payload, label }) => {
return null;
};
const MonitorDetailsAreaChart = ({ checks, filter }) => {
const MonitorDetailsAreaChart = ({ checks }) => {
// SQUASH ERROR, NOT PERMANENT SOLUTION
const error = console.error;
console.error = (...args) => {
@@ -47,45 +46,12 @@ const MonitorDetailsAreaChart = ({ checks, filter }) => {
});
};
const filterChecks = (checks, filter, numToDisplay) => {
const limits = {
day: 24 * 60 * 60 * 1000,
week: 24 * 60 * 60 * 1000 * 7,
month: 24 * 60 * 60 * 1000 * 30, //TODO better monthly calculations
};
const now = new Date().getTime();
let result = [];
for (let i = 0; i < checks.length; i++) {
const checkTime = new Date(checks[i].createdAt).getTime();
if (now - checkTime < limits[filter]) {
result.push(checks[i]);
}
}
// If more than numToDisplay checks, pick every nth check
if (result.length > numToDisplay) {
const n = Math.ceil(result.length / numToDisplay);
result = result.filter((_, idx) => {
return idx % n === 0;
});
}
return result;
};
let normalizedChecks = [];
if (checks && checks.length > 0) {
const filteredChecks = filterChecks(checks, filter, 75);
normalizedChecks = NormalizeData(filteredChecks, 10, 100);
}
return (
<ResponsiveContainer width="100%" height="100%">
<AreaChart
width={500}
height={400}
data={normalizedChecks}
data={checks}
margin={{
top: 10,
right: 0,
@@ -1,21 +1,19 @@
import "./index.css";
import PropTypes from "prop-types";
import { BarChart, Bar, ResponsiveContainer, Cell } from "recharts";
import { NormalizeData } from "../ChartUtils";
const ResponseTimeChart = ({ checks = [] }) => {
const normalizedChecks = NormalizeData(checks, 1, 100);
return (
<div className="chart-container">
<ResponsiveContainer width="100%" height="100%">
<BarChart
width={150}
height={40}
data={normalizedChecks}
data={checks}
style={{ cursor: "pointer" }}
>
<Bar maxBarSize={10} dataKey="responseTime">
{normalizedChecks.map((check, index) => (
{checks.map((check, index) => (
<Cell
key={`cell-${index}`}
fill={
@@ -51,7 +51,7 @@ export const getUptimeMonitorsByUserId = createAsyncThunk(
const user = jwtDecode(token);
try {
const res = await axiosInstance.get(
`/monitors/user/${user._id}?limit=25&type=http&type=ping&sortOrder=desc`,
`/monitors/user/${user._id}?limit=25&type=http&type=ping&sortOrder=desc&normalize=true`,
{
headers: {
Authorization: `Bearer ${token}`,
+74 -3
View File
@@ -1,4 +1,4 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useState, useCallback } from "react";
import PropTypes from "prop-types";
import { Box, Skeleton, Stack, Typography, useTheme } from "@mui/material";
import { useSelector } from "react-redux";
@@ -115,6 +115,74 @@ const DetailsPage = () => {
const { monitorId } = useParams();
const { authToken } = useSelector((state) => state.auth);
const [filter, setFilter] = useState("day");
const navigate = useNavigate();
const fetchDataForTable = useCallback(async () => {
try {
const limit = 0;
const res = await axiosInstance.get(
`/monitors/${monitorId}?sortOrder=asc&limit=${limit}`,
{
headers: {
Authorization: `Bearer ${authToken}`,
},
}
);
const data = {
cols: [
{ id: 1, name: "Status" },
{ id: 2, name: "Date & Time" },
{ id: 3, name: "Message" },
],
rows: res.data.data.checks.map((check, idx) => {
const status = check.status === true ? "up" : "down";
return {
id: check._id,
data: [
{
id: idx,
data: (
<StatusLabel
status={status}
text={status}
customStyles={{ textTransform: "capitalize" }}
/>
),
},
{
id: idx + 1,
data: new Date(check.createdAt).toLocaleString(),
},
{ id: idx + 2, data: check.statusCode },
],
};
}),
};
setData(data);
} catch (error) {
console.log(error);
}
}, [authToken, monitorId]);
const fetchMonitor = useCallback(async () => {
try {
const res = await axiosInstance.get(
`/monitors/${monitorId}?sortOrder=asc&filter=${filter}&numToDisplay=50&normalize=true`,
{
headers: {
Authorization: `Bearer ${authToken}`,
},
}
);
setMonitor(res.data.data);
} catch (error) {
console.error("Error fetching monitor of id: " + monitorId);
navigate("/not-found");
}
}, [authToken, monitorId, navigate, filter]);
const fetchDataForChart = async () => {
try {
@@ -185,14 +253,17 @@ const DetailsPage = () => {
useEffect(() => {
fetchMonitor();
}, [monitorId, authToken]);
}, [fetchMonitor]);
useEffect(() => {
fetchDataForTable();
}, [fetchDataForTable]);
useEffect(() => {
fetchDataForChart();
}, [filter]);
const theme = useTheme();
const navigate = useNavigate();
/**
* Function to calculate uptime duration based on the most recent check.
+1 -1
View File
@@ -145,7 +145,7 @@ const Monitors = () => {
useEffect(() => {
dispatch(getUptimeMonitorsByUserId(authState.authToken));
}, []);
}, [authState.authToken, dispatch]);
const up = monitorState.monitors.reduce((acc, cur) => {
return cur.status === true ? acc + 1 : acc;