initial commit

This commit is contained in:
Alex Holliday committed 2025-11-13 13:47:26 -08:00
1 parent 7cb985116e
commit 75acf7b38f
955 files changed
+37333 -87054

No files matched your search

@@ -0,0 +1,62 @@
import { monitorSchemaInfra } from "@/validation/zod";
import { useGet, usePatch } from "@/hooks/UseApi";
import { InfraForm } from "@/pages/infrastructure/InfraForm";
import { useParams } from "react-router";
import type { ApiResponse } from "@/hooks/UseApi";
import humanInterval from "human-interval";
import { z } from "zod";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
import type { IMonitor } from "@/types/monitor";
const InfraConfigurePage = () => {
type FormValues = z.infer<typeof monitorSchemaInfra>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const { id } = useParams();
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { response: monitorResponse } = useGet<ApiResponse<any>>(
`/monitors/${id}`
);
const monitor = monitorResponse?.data || null;
const notificationOptions = response?.data ?? [];
const { patch, loading, error } = usePatch<Partial<SubmitValues>, IMonitor>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 180000;
const submitData = {
type: data.type,
secret: data.secret,
name: data.name,
notificationChannels: data.notificationChannels,
interval,
};
const result = await patch(`/monitors/${id}`, submitData);
if (result) {
navigate(`/infrastructure/${id}`);
} else {
console.error(error);
}
};
return (
<InfraForm
mode="configure"
initialData={{
...monitor,
}}
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default InfraConfigurePage;
@@ -0,0 +1,43 @@
import { InfraForm } from "@/pages/infrastructure/InfraForm";
import humanInterval from "human-interval";
import { z } from "zod";
import { monitorSchemaInfra } from "@/validation/zod";
import { useGet, usePost } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import { useNavigate } from "react-router";
import type { INotificationChannel } from "@/types/notification-channel";
const InfraCreatePage = () => {
type FormValues = z.infer<typeof monitorSchemaInfra>;
type SubmitValues = Omit<FormValues, "interval"> & {
interval: number | undefined;
};
const navigate = useNavigate();
const { response } = useGet<ApiResponse<INotificationChannel[]>>(
"/notification-channels"
);
const { post, loading, error } = usePost<SubmitValues, any>();
const onSubmit = async (data: FormValues) => {
let interval = humanInterval(data.interval);
if (!interval) interval = 60000;
const submitData = { ...data, interval };
const result = await post("/monitors", submitData);
if (result) {
navigate("/infrastructure");
} else {
console.error(error);
}
};
const notificationOptions = response?.data ?? [];
return (
<InfraForm
onSubmit={onSubmit}
notificationOptions={notificationOptions}
loading={loading}
/>
);
};
export default InfraCreatePage;
@@ -0,0 +1,126 @@
import { BasePage, StatBox } from "@/components/design-elements";
import { HeaderControls, HeaderRange } from "@/components/monitors";
import Stack from "@mui/material/Stack";
import prettyMilliseconds from "pretty-ms";
import { getStatusPalette } from "@/utils/MonitorUtils";
import { InfraDetailsGraphs } from "@/pages/infrastructure/InfraDetailsGraphs";
import { useGet, usePatch } from "@/hooks/UseApi";
import { useState } from "react";
import { useTheme } from "@mui/material/styles";
import { useParams } from "react-router";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMonitor, IMonitorWithMonitorStats } from "@/types/monitor";
import type { IInfraCheck } from "@/types/check";
import {
getFrequency,
getCores,
getAvgTemp,
getGbs,
getDiskTotalGbs,
getOsAndPlatform,
} from "@/pages/infrastructure/InfraUtils";
import { InfraDetailsGauges } from "./InfraDetailsGauges";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const InfraDetailsPage = () => {
const theme = useTheme();
const { id } = useParams();
const [range, setRange] = useState("2h");
const { response, isValidating, refetch } = useGet<
ApiResponse<IMonitorWithMonitorStats>
>(
`/monitors/${id}?embedChecks=true&range=${range}`,
{},
{ refreshInterval: GLOBAL_REFRESH, keepPreviousData: true }
);
const { patch, loading: isPatching } = usePatch<any, IMonitor>();
const monitor = response?.data?.monitor;
const stats = response?.data?.stats;
const checks = (response?.data?.checks || []) as IInfraCheck[];
const palette = getStatusPalette(monitor?.status || "initializing");
const streakDuration = stats?.currentStreakStartedAt
? Date.now() - stats?.currentStreakStartedAt
: 0;
const lastChecked = stats?.lastCheckTimestamp
? Date.now() - stats?.lastCheckTimestamp
: -1;
if (!monitor) {
return null;
}
return (
<BasePage>
<HeaderControls
monitor={monitor}
patch={patch}
isPatching={isPatching}
refetch={refetch}
path="/infrastructure"
/>
<Stack direction="row" gap={theme.spacing(8)} flexWrap={"wrap"}>
<StatBox
palette={palette}
title="Active for"
subtitle={prettyMilliseconds(streakDuration, {
secondsDecimalDigits: 0,
})}
/>
<StatBox
title="Last check"
subtitle={
lastChecked >= 0
? `${prettyMilliseconds(lastChecked, {
secondsDecimalDigits: 0,
})} ago`
: "N/A"
}
/>
<StatBox
title="Last response time"
subtitle={
stats?.lastResponseTime ? `${stats?.lastResponseTime} ms` : "N/A"
}
/>
<StatBox
title="CPU (physical)"
subtitle={getCores(checks[0]?.cpu?.physical_core)}
/>
<StatBox
title="CPU (logical)"
subtitle={getCores(checks[0]?.cpu?.logical_core)}
/>
<StatBox
title="CPU frequency"
subtitle={getFrequency(checks[0]?.cpu?.current_frequency)}
/>
<StatBox
title="Avg CPU temp"
subtitle={getAvgTemp(checks[0]?.cpu?.temperature)}
/>
<StatBox
title="Memory"
subtitle={getGbs(checks[0]?.memory?.total_bytes)}
/>
<StatBox title="Disk" subtitle={getDiskTotalGbs(checks[0]?.disk)} />
<StatBox title="OS" subtitle={getOsAndPlatform(checks[0]?.host)} />
</Stack>
{/* <Typography variant="h1">Infrastructure overview</Typography> */}
<InfraDetailsGauges checks={checks} />
<HeaderRange loading={isValidating} range={range} setRange={setRange} />
<InfraDetailsGraphs checks={checks} range={range} />
{/* <Typography variant="h1">Network</Typography>
<InfraDetailsNetGraphs checks={checks} range={range} /> */}
</BasePage>
);
};
export default InfraDetailsPage;
@@ -0,0 +1,84 @@
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
import { BaseChart } from "@/components/monitors/Chart";
import { Gauge } from "@/components/design-elements";
import { getGbs, getFrequency } from "./InfraUtils";
import type { IInfraCheck } from "@/types/check";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
const InfraDetailGauge = ({
title,
progress,
upperLabel,
upperValue,
lowerLabel,
lowerValue,
}: {
title: string;
progress: number;
upperLabel?: string;
upperValue?: string | number;
lowerLabel?: string;
lowerValue?: string | number;
}) => {
const theme = useTheme();
return (
<BaseChart icon={null} title={title} maxWidth={225}>
<Stack alignItems={"center"} mb={theme.spacing(4)} gap={theme.spacing(4)}>
<Gauge progress={progress} />
</Stack>
<Stack direction={"row"} justifyContent={"space-between"}>
<Typography>{upperLabel}</Typography>
<Typography>{upperValue}</Typography>
</Stack>
<Stack direction={"row"} justifyContent={"space-between"}>
<Typography>{lowerLabel}</Typography>
<Typography>{lowerValue}</Typography>
</Stack>
</BaseChart>
);
};
export const InfraDetailsGauges = ({ checks }: { checks: IInfraCheck[] }) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
return (
<Stack
direction={isSmall ? "column" : "row"}
spacing={theme.spacing(8)}
alignItems={"center"}
>
<InfraDetailGauge
title="Memory Usage"
progress={(checks[0]?.memory.usage_percent || 0) * 100}
upperLabel="Used"
upperValue={getGbs(checks[0]?.memory.used_bytes)}
lowerLabel="Free"
lowerValue={getGbs(checks[0]?.memory.total_bytes)}
/>
<InfraDetailGauge
title="CPU Usage"
progress={(checks[0]?.cpu.usage_percent || 0) * 100}
upperLabel="Current frequency"
upperValue={getFrequency(checks[0]?.cpu.current_frequency)}
lowerLabel="Max Frequency"
lowerValue={getFrequency(checks[0]?.cpu.frequency)}
/>
{checks[0]?.disk?.map((disk, idx) => {
return (
<InfraDetailGauge
key={disk.device + idx}
title={`Disk ${idx} usage`}
progress={(disk.usage_percent || 0) * 100}
upperLabel="Used"
upperValue={getGbs(disk.used_bytes)}
lowerLabel="Free"
lowerValue={getGbs(disk.total_bytes)}
/>
);
})}
</Stack>
);
};
@@ -0,0 +1,86 @@
import Grid from "@mui/material/Grid";
import { HistogramInfrastructure } from "@/components/monitors";
import type { IInfraCheck } from "@/types/check";
import { useMemo } from "react";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
const getChartConfigs = (theme: any, checks: IInfraCheck[]) => {
return [
{
type: "memory",
dataKeys: ["memory.usage_percent"],
strokeColor: theme.palette.accent.main,
gradientStartColor: theme.palette.accent.main,
yDomain: [0, 1],
idx: null,
},
{
type: "cpu",
dataKeys: ["cpu.used_percent"],
strokeColor: theme.palette.success.main,
gradientStartColor: theme.palette.success.main,
yDomain: [0, 1],
idx: null,
},
{
type: "temp",
dataKeys: ["avg_temp"],
strokeColor: theme.palette.error.main,
gradientStartColor: theme.palette.error.main,
yDomain: [0, 150],
idx: null,
},
...(checks[0]?.disk?.map((_, idx) => ({
type: "disk",
dataKeys: [`disk[${idx}].usage_percent`],
strokeColor: theme.palette.warning.main,
gradientStartColor: theme.palette.warning.main,
yDomain: [0, 1],
idx,
})) || []),
];
};
export const InfraDetailsGraphs = ({
checks,
range,
}: {
checks: IInfraCheck[];
range: string;
}) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const chartConfigs = useMemo(
() => getChartConfigs(theme, checks),
[theme, checks]
);
return (
<Grid container spacing={theme.spacing(8)}>
{chartConfigs.map((config) => {
return (
<Grid
size={isSmall ? 12 : 6}
key={`${config.type}-${config.idx ?? ""}`}
>
<HistogramInfrastructure
range={range}
title={config.type}
idx={config.idx}
key={`${config.type}-${config.idx ?? ""}`}
checks={checks}
xKey="_id"
yDomain={config.yDomain}
dataKeys={config.dataKeys}
gradient={true}
gradientStartColor={config.gradientStartColor}
gradientEndColor="#ffffff"
strokeColor={config.strokeColor}
/>
</Grid>
);
})}
</Grid>
);
};
@@ -0,0 +1,124 @@
import Stack from "@mui/material/Stack";
import MenuItem from "@mui/material/MenuItem";
import Grid from "@mui/material/Grid";
import { HistogramInfrastructure } from "@/components/monitors";
import { Select } from "@/components/inputs";
import type { IInfraCheck } from "@/types/check";
import { useMemo, useState, useEffect } from "react";
import { useTheme } from "@mui/material/styles";
import useMediaQuery from "@mui/material/useMediaQuery";
const getChartConfigs = (
theme: any,
checks: IInfraCheck[],
selectedInterface: string
) => {
const idx = checks[0]?.net.findIndex((i) => i.name === selectedInterface);
if (idx === -1) return [];
return [
{
type: "Bytes received",
dataKeys: [`net[${idx}].bytes_recv`],
strokeColor: theme.palette.accent.main,
gradientStartColor: theme.palette.accent.main,
yDomain: [0, 1],
idx: null,
},
{
type: "Bytes sent",
dataKeys: [`net[${idx}].bytes_sent`],
strokeColor: theme.palette.success.main,
gradientStartColor: theme.palette.success.main,
yDomain: [0, 1],
idx: null,
},
{
type: "Packets received",
dataKeys: [`net[${idx}].packets_recv`],
strokeColor: theme.palette.warning.main,
gradientStartColor: theme.palette.warning.main,
yDomain: [0, 1],
idx: null,
},
{
type: "Packets sent",
dataKeys: [`net[${idx}].packets_sent`],
strokeColor: theme.palette.error.main,
gradientStartColor: theme.palette.error.main,
yDomain: [0, 1],
idx: null,
},
];
};
export const InfraDetailsNetGraphs = ({
checks,
range,
}: {
checks: IInfraCheck[];
range: string;
}) => {
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const [selectedInterface, setSelectedInterface] = useState<string>("");
const chartConfigs = useMemo(
() => getChartConfigs(theme, checks, selectedInterface),
[theme, checks, selectedInterface]
);
useEffect(() => {
if (checks[0]) {
const firstNonLoopback = checks[0].net.find(
(iface) => iface.name !== "lo"
);
setSelectedInterface(firstNonLoopback?.name || "");
}
}, [checks]);
return (
<Stack gap={theme.spacing(8)}>
<Grid container spacing={theme.spacing(8)}>
<Grid size={4}>
<Select
fullWidth
value={selectedInterface}
onChange={(e) => setSelectedInterface(e.target.value)}
>
{checks[0]?.net.map((iface) => {
return (
<MenuItem key={iface.name} value={iface.name}>
{iface.name}
</MenuItem>
);
})}
</Select>
</Grid>
<Grid size={8} />
{chartConfigs.map((config) => {
return (
<Grid
size={isSmall ? 12 : 6}
key={`${config.type}-${config.idx ?? ""}`}
>
<HistogramInfrastructure
range={range}
title={config.type}
idx={config.idx}
key={`${config.type}-${config.idx ?? ""}`}
checks={checks}
xKey="_id"
yDomain={config.yDomain}
dataKeys={config.dataKeys}
gradient={true}
gradientStartColor={config.gradientStartColor}
gradientEndColor="#ffffff"
strokeColor={config.strokeColor}
/>
</Grid>
);
})}
</Grid>
</Stack>
);
};
@@ -0,0 +1,293 @@
import Stack from "@mui/material/Stack";
import {
TextInput,
Button,
RadioWithDescription,
AutoComplete,
} from "@/components/inputs";
import RadioGroup from "@mui/material/RadioGroup";
import { ConfigBox, BasePage } from "@/components/design-elements";
import { Trash2 } from "lucide-react";
import { Typography } from "@mui/material";
import { useEffect, useState, useRef } from "react";
import { useTranslation } from "react-i18next";
import { monitorSchemaInfra } from "@/validation/zod";
import { z } from "zod";
import { zodResolver } from "@hookform/resolvers/zod";
import {
useForm,
Controller,
useWatch,
type SubmitHandler,
} from "react-hook-form";
import { useTheme } from "@mui/material/styles";
import { useInitForm } from "@/hooks/forms/UseInitInfraForm";
type FormValues = z.infer<typeof monitorSchemaInfra>;
export const InfraForm = ({
mode = "create",
initialData,
onSubmit,
notificationOptions,
loading,
}: {
mode?: "create" | "configure";
initialData?: Partial<FormValues>;
onSubmit: SubmitHandler<FormValues>;
notificationOptions: any[];
loading: boolean;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const { defaults } = useInitForm({ initialData: initialData });
const urlInputRef = useRef<HTMLInputElement>(null);
const [selectedProtocol, setSelectedProtocol] = useState<string>("https");
const {
handleSubmit,
control,
setValue,
reset,
formState: { errors },
} = useForm<FormValues>({
resolver: zodResolver(monitorSchemaInfra) as any,
defaultValues: defaults,
mode: "onChange",
});
const url = useWatch({ control, name: "url" });
useEffect(() => {
reset(defaults);
if (defaults.url.startsWith("http://")) {
setSelectedProtocol("http");
}
}, [initialData, reset, defaults]);
useEffect(() => {
if (!url) {
setValue("url", `${selectedProtocol}://`);
}
const hasProtocol = /^(http|https):\/\//i.test(url);
if (hasProtocol) {
const newUrl = url.replace(
/^(http|https):\/\//i,
`${selectedProtocol}://`
);
if (newUrl !== url) setValue("url", newUrl);
} else {
setValue("url", `${selectedProtocol}://${url}`);
}
}, [selectedProtocol, setValue, url]);
useEffect(() => {
const input = urlInputRef.current;
if (input) {
const len = input.value.length;
input.setSelectionRange(len, len);
}
}, [selectedProtocol]);
const notificationChannels = useWatch({
control,
name: "notificationChannels",
});
return (
<BasePage component={"form"} onSubmit={handleSubmit(onSubmit)}>
<ConfigBox
title={t("settingsGeneralSettings")}
subtitle={t(`pageSpeedConfigureSettingsDescription`)}
rightContent={
<Stack gap={theme.spacing(8)}>
<RadioGroup
value={selectedProtocol}
sx={{ gap: theme.spacing(6) }}
onChange={(e) => {
setSelectedProtocol(e.target.value);
}}
>
<RadioWithDescription
value="https"
label="HTTPS"
description=""
/>
<RadioWithDescription
value="http"
label={"HTTP"}
description={""}
/>
</RadioGroup>
<Controller
disabled={mode === "configure"}
name="url"
control={control}
render={({ field }) => (
<TextInput
inputRef={urlInputRef}
{...field}
onFocus={(e) => {
const input = e.target;
setTimeout(() => {
input.setSelectionRange(
input.value.length,
input.value.length
);
}, 0);
}}
type="text"
fieldLabel={t("url")}
fullWidth
error={!!errors.url}
helperText={errors.url ? errors.url.message : ""}
/>
)}
/>
<Controller
name="name"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("displayName")}
fullWidth
error={!!errors.name}
helperText={errors.name ? errors.name.message : ""}
/>
)}
/>
<Controller
name="secret"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("infrastructureAuthorizationSecretLabel")}
fullWidth
error={!!errors.secret}
helperText={errors.secret ? errors.secret.message : ""}
/>
)}
/>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.incidentConfigTitle")}
subtitle={t("createMonitorPage.incidentConfigDescriptionV2")}
rightContent={
<Controller
name="n"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="number"
fieldLabel={t("createMonitorPage.incidentConfigStatusCheckNumber")}
fullWidth
error={!!errors.n}
helperText={errors.n ? errors.n.message : ""}
onChange={(e) => {
const target = e.target as HTMLInputElement;
field.onChange(target.valueAsNumber);
}}
/>
)}
/>
}
/>
<ConfigBox
title={t("notificationConfig.title")}
subtitle={t("notificationConfig.description")}
rightContent={
<Stack>
<Controller
name="notificationChannels"
control={control}
defaultValue={[]}
render={({ field }) => (
<AutoComplete
multiple
options={notificationOptions}
getOptionLabel={(option) => option.name}
value={notificationOptions.filter((o: any) =>
(field.value || []).includes(o._id)
)}
onChange={(_, newValue) => {
field.onChange(newValue.map((o: any) => o._id));
}}
/>
)}
/>
<Stack gap={theme.spacing(2)} mt={theme.spacing(2)}>
{notificationChannels.map((notificationId) => {
const option = notificationOptions.find(
(o: any) => o._id === notificationId
);
if (!option) return null;
return (
<Stack
width={"100%"}
justifyContent={"space-between"}
direction="row"
key={notificationId}
>
<Typography>{option.name}</Typography>
<Trash2
size={20}
strokeWidth={1.5}
onClick={() => {
const updated = notificationChannels.filter(
(id) => id !== notificationId
);
setValue("notificationChannels", updated);
}}
style={{ cursor: "pointer" }}
/>
</Stack>
);
})}
</Stack>
</Stack>
}
/>
<ConfigBox
title={t("createMonitorPage.intervalTitle")}
subtitle="How often to check the URL"
rightContent={
<Controller
name="interval"
control={control}
render={({ field }) => (
<TextInput
{...field}
type="text"
fieldLabel={t("createMonitorPage.intervalDescription")}
fullWidth
error={!!errors.interval}
helperText={errors.interval ? errors.interval.message : ""}
/>
)}
/>
}
/>
<Stack direction="row" justifyContent="flex-end">
<Button
loading={loading}
type="submit"
variant="contained"
color="accent"
>
{t("settingsSave")}
</Button>
</Stack>
</BasePage>
);
};
@@ -0,0 +1,102 @@
import {
MonitorBasePageWithStates,
UpStatusBox,
DownStatusBox,
PausedStatusBox,
InfoBox,
} from "@/components/design-elements";
import { HeaderCreate } from "@/components/monitors";
import Stack from "@mui/material/Stack";
import { Dialog } from "@/components/inputs";
import { InfraMonitorsTable } from "./InfraMonitorsTable";
import { useTranslation } from "react-i18next";
import { useTheme } from "@mui/material/styles";
import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/hooks/UseApi";
import type { IMonitor, IMonitorWithStats } from "@/types/monitor";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useState } from "react";
import { useDelete } from "@/hooks/UseApi";
const GLOBAL_REFRESH = import.meta.env.VITE_APP_GLOBAL_REFRESH;
const PageSpeedMonitorsPage = () => {
const theme = useTheme();
const { t } = useTranslation();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const [selectedMonitor, setSelectedMonitor] = useState<IMonitor | null>(null);
const isDialogOpen = Boolean(selectedMonitor);
const [page, setPage] = useState(0);
const [rowsPerPage, setRowsPerPage] = useState(10);
const { deleteFn } = useDelete();
const { response, loading, isValidating, error, refetch } = useGet<
ApiResponse<IMonitorWithStats>
>(
`/monitors?embedChecks=true&type=infrastructure&page=${page}&rowsPerPage=${rowsPerPage}`,
{},
{
refreshInterval: GLOBAL_REFRESH,
keepPreviousData: true,
dedupingInterval: 0,
},
{
useTeamIdAsKey: true,
}
);
const monitors: IMonitor[] = response?.data?.monitors ?? ([] as IMonitor[]);
const count = response?.data?.count || 0;
const upCount = response?.data?.upCount || 0;
const downCount = response?.data?.downCount || 0;
const pausedCount = response?.data?.pausedCount || 0;
const handleConfirm = async () => {
await deleteFn(`/monitors/${selectedMonitor?._id}`);
setSelectedMonitor(null);
refetch();
};
const handleCancel = () => {
setSelectedMonitor(null);
};
return (
<MonitorBasePageWithStates
loading={isValidating}
error={error}
items={monitors}
page="infrastructure"
actionLink="/infrastructure/create"
>
<InfoBox
title="Server Health Monitoring"
description="Keep track of your servers' vital statistics including CPU usage, memory, disk space, and network performance. Receive alerts when resources run low."
/>
<HeaderCreate isLoading={loading} path="/infrastructure/create" />
<Stack direction={isSmall ? "column" : "row"} gap={theme.spacing(8)}>
<UpStatusBox n={upCount} />
<DownStatusBox n={downCount} />
<PausedStatusBox n={pausedCount} />
</Stack>
<InfraMonitorsTable
monitors={monitors}
refetch={refetch}
setSelectedMonitor={setSelectedMonitor}
count={count}
page={page}
setPage={setPage}
rowsPerPage={rowsPerPage}
setRowsPerPage={setRowsPerPage}
/>
<Dialog
open={isDialogOpen}
title={t("deleteDialogTitle")}
content={t("deleteDialogDescription")}
onConfirm={handleConfirm}
onCancel={handleCancel}
/>
</MonitorBasePageWithStates>
);
};
export default PageSpeedMonitorsPage;
@@ -0,0 +1,202 @@
import Box from "@mui/material/Box";
import Typography from "@mui/material/Typography";
import { Table, Pagination, StatusLabel } from "@/components/design-elements";
import type { Header } from "@/components/design-elements/Table";
import { ActionsMenu } from "@/components/actions-menu";
import { Gauge } from "@/components/design-elements";
import { useTranslation } from "react-i18next";
import useMediaQuery from "@mui/material/useMediaQuery";
import { useTheme } from "@mui/material/styles";
import { useNavigate } from "react-router-dom";
import { usePatch } from "@/hooks/UseApi";
import type { IMonitor } from "@/types/monitor";
import type { ActionMenuItem } from "@/components/actions-menu";
export const InfraMonitorsTable = ({
monitors,
refetch,
setSelectedMonitor,
count,
page,
setPage,
rowsPerPage,
setRowsPerPage,
}: {
monitors: IMonitor[];
refetch: Function;
setSelectedMonitor: Function;
count: number;
page: number;
setPage: (page: number) => void;
rowsPerPage: number;
setRowsPerPage: (rowsPerPage: number) => void;
}) => {
const { t } = useTranslation();
const theme = useTheme();
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
const navigate = useNavigate();
const {
patch,
// loading: isPatching,
// error: postError,
} = usePatch<any, IMonitor>();
const handlePageChange = (
_e: React.MouseEvent<HTMLButtonElement> | null,
newPage: number
) => {
setPage(newPage);
};
const handleRowsPerPageChange = (
e: React.ChangeEvent<HTMLTextAreaElement | HTMLInputElement>
) => {
const value = Number(e.target.value);
setPage(0);
setRowsPerPage(value);
};
const getActions = (monitor: IMonitor): ActionMenuItem[] => {
return [
{
id: 1,
label: "Open site",
action: () => {
window.open(monitor.url, "_blank", "noreferrer");
},
closeMenu: true,
},
{
id: 2,
label: "Details",
action: () => {
navigate(`${monitor._id}`);
},
},
{
id: 3,
label: "Incidents",
action: () => {
navigate(`/incidents/${monitor._id}`);
},
},
{
id: 4,
label: "Configure",
action: () => {
navigate(`/infrastructure/${monitor._id}/configure`);
},
},
// {
// id: 5,
// label: "Clone",
// action: () => {
// console.log("Open clone");
// },
// },
{
id: 6,
label: monitor.isActive ? "Pause" : "Resume",
action: async () => {
await patch(`/monitors/${monitor._id}/active`);
refetch();
},
closeMenu: true,
},
{
id: 7,
label: <Typography color={theme.palette.error.main}>Remove</Typography>,
action: () => {
setSelectedMonitor(monitor);
},
closeMenu: true,
},
];
};
const getHeaders = () => {
const headers: Header<IMonitor>[] = [
{
id: "name",
content: t("host"),
render: (row) => {
return row.name;
},
},
{
id: "status",
content: t("status"),
render: (row) => {
return <StatusLabel status={row.status} isActive={row.isActive} />;
},
},
{
id: "cpu",
content: t("cpu"),
render: (row) => {
const cpuUsage =
(row.latestChecks?.[0]?.system?.cpu?.usage_percent || 0) * 100;
return <Gauge progress={cpuUsage} />;
},
},
{
id: "memory",
content: t("memory"),
render: (row) => {
const memoryUsage =
(row.latestChecks?.[0]?.system?.memory?.usage_percent || 0) * 100;
return <Gauge progress={memoryUsage} />;
},
},
{
id: "disk",
content: t("disk"),
render: (row) => {
const totalDiskUsage = row.latestChecks?.[0]?.system?.disk.reduce(
(acc, disk) => acc + disk.usage_percent,
0
);
const diskCount = row.latestChecks?.[0]?.system?.disk.length || 1;
const diskUsage = ((totalDiskUsage || 0) / diskCount) * 100;
return <Gauge progress={diskUsage} />;
},
},
{
id: "actions",
content: t("actions"),
render: (row) => {
return <ActionsMenu items={getActions(row)} />;
},
},
];
return headers;
};
let headers = getHeaders();
if (isSmall) {
headers = headers.filter((h) => h.id !== "histogram");
}
return (
<Box>
<Table
headers={headers}
data={monitors}
onRowClick={(row) => {
navigate(`/infrastructure/${row._id}`);
}}
/>
<Pagination
component="div"
count={count}
page={page}
rowsPerPage={rowsPerPage}
onPageChange={handlePageChange}
onRowsPerPageChange={handleRowsPerPageChange}
/>
</Box>
);
};
@@ -0,0 +1,49 @@
import type { IDiskInfo, IHostInfo } from "@/types/check";
export const getFrequency = (frequency: number): string => {
if (!frequency) return "N/A";
const ghz = (frequency / 1000).toFixed(2);
return `${ghz} GHz`;
};
export const getCores = (cores: number) => {
if (!cores) return "N/A";
if (cores === 1) return `${cores} core`;
return `${cores} cores`;
};
export const getAvgTemp = (temps: number[]): string => {
if (!temps || temps.length === 0) return "N/A";
const avgTemp = temps.reduce((a, b) => a + b, 0) / temps.length;
return `${avgTemp.toFixed(2)} °C`;
};
export const getGbs = (bytes: number): string => {
if (!bytes) {
return "N/A";
}
if (bytes === 0) {
return "0 GB";
}
const GB = bytes / (1024 * 1024 * 1024);
const MB = bytes / (1024 * 1024);
if (GB >= 1) {
return GB.toFixed(2) + " GB";
} else {
return MB.toFixed(2) + " MB";
}
};
export const getDiskTotalGbs = (disk: IDiskInfo[]): string => {
const totalBytes =
disk?.reduce((acc, disk) => acc + (disk.total_bytes || 0), 0) || 0;
return getGbs(totalBytes);
};
export const getOsAndPlatform = (hostInfo: IHostInfo): string => {
const os = hostInfo?.pretty_name || hostInfo?.os || "N/A";
const platform = hostInfo?.platform || "N/A";
return `${os} (${platform})`;
};