fix: minor refactoring infrastructureMetrics

This commit is contained in:
mannilakash committed 2026-03-17 06:02:23 -04:00
1 parent d1077a1314
commit c27393942e
2 files changed
+153 -94

No files matched your search

+26 -13
View File
@@ -21,7 +21,7 @@ import {
import { useTheme } from "@mui/material/styles"; import { useTheme } from "@mui/material/styles";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { useEffect, useState } from "react"; import { useEffect, useMemo, useState } from "react";
import { useForm, Controller } from "react-hook-form"; import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod"; import { zodResolver } from "@hookform/resolvers/zod";
import { useStatusPageForm } from "@/Hooks/useStatusPageForm"; import { useStatusPageForm } from "@/Hooks/useStatusPageForm";
@@ -39,6 +39,22 @@ interface TimezoneOption {
name: string; name: string;
} }
const MONITOR_TYPE_KEYS: Record<string, string> = {
http: "pages.common.monitors.monitorTypes.optionHttp",
ping: "pages.common.monitors.monitorTypes.optionPing",
docker: "pages.common.monitors.monitorTypes.optionDocker",
port: "pages.common.monitors.monitorTypes.optionPort",
game: "pages.common.monitors.monitorTypes.optionGame",
grpc: "pages.common.monitors.monitorTypes.optionGrpc",
websocket: "pages.common.monitors.monitorTypes.optionWebSocket",
hardware: "pages.common.monitors.monitorTypes.optionHardware",
};
const getMonitorTypeLabel = (type: string, t: (key: string) => string): string => {
const i18nMonitorKey = MONITOR_TYPE_KEYS[type];
return i18nMonitorKey ? t(i18nMonitorKey) : type;
};
const CreateStatusPage = () => { const CreateStatusPage = () => {
const theme = useTheme(); const theme = useTheme();
const { t } = useTranslation(); const { t } = useTranslation();
@@ -84,25 +100,22 @@ const CreateStatusPage = () => {
}, [defaults, reset]); }, [defaults, reset]);
const watchedMonitorIds: string[] = form.watch("monitors") ?? []; const watchedMonitorIds: string[] = form.watch("monitors") ?? [];
useEffect(() => { const computedTypes: MonitorDisplayType[] = useMemo(() => {
const selectedMonitors = (watchedMonitorIds ?? []) const selectedMonitors = (watchedMonitorIds ?? [])
.map((id) => monitors.find((m) => m.id === id)) .map((id) => monitors.find((m) => m.id === id))
.filter((m): m is Monitor => m !== undefined); .filter((m): m is Monitor => m !== undefined);
const typesSet: Set<MonitorDisplayType> = new Set(); const typesSet = new Set<MonitorDisplayType>();
selectedMonitors.forEach((m) => { selectedMonitors.forEach((m) => {
if (m.type === "hardware") { typesSet.add(m.type === "hardware" ? "infrastructure" : "uptime");
typesSet.add("infrastructure");
} else {
typesSet.add("uptime");
}
}); });
const computedTypes: MonitorDisplayType[] = typesSet.size return typesSet.size ? Array.from(typesSet) : ["uptime"];
? Array.from(typesSet) }, [JSON.stringify(watchedMonitorIds), monitors]);
: ["uptime"];
useEffect(() => {
form.setValue("type", computedTypes); form.setValue("type", computedTypes);
}, [watchedMonitorIds, monitors, form]); }, [computedTypes]);
const onError = (errors: any) => { const onError = (errors: any) => {
logger.debug("Status page validation errors", errors); logger.debug("Status page validation errors", errors);
@@ -332,7 +345,7 @@ const CreateStatusPage = () => {
<GripVertical size={20} /> <GripVertical size={20} />
<Typography <Typography
flexGrow={1} flexGrow={1}
>{`${monitor.name} (${t(`pages.common.monitors.monitorTypes.option${monitor?.type.charAt(0).toUpperCase() + monitor?.type.slice(1)}`)})`}</Typography> >{`${monitor.name} (${getMonitorTypeLabel(monitor.type, t)})`}</Typography>
<IconButton <IconButton
size="small" size="small"
onClick={() => { onClick={() => {
@@ -10,19 +10,28 @@ import useMediaQuery from "@mui/material/useMediaQuery";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import { LAYOUT, SPACING } from "@/Utils/Theme/constants"; import { LAYOUT, SPACING } from "@/Utils/Theme/constants";
const GAUGE_RADIUS = 60;
const GAUGE_STROKE_WIDTH = 12;
const PERCENTAGE_MULTIPLIER = 100;
interface StatusPageMonitor extends Monitor { interface StatusPageMonitor extends Monitor {
checks?: Monitor["recentChecks"]; checks?: Monitor["recentChecks"];
infrastructureCPU?: number;
infrastructureMemory?: number;
infrastructureDisk?: number;
} }
interface MetricDetailRowProps { interface MetricDetail {
label: string; label: string;
value: string; value: string;
} }
const MetricDetailRow = ({ label, value }: MetricDetailRowProps) => { interface MetricConfig {
key: string;
label: string;
hasData: boolean;
progress: number;
details: MetricDetail[];
}
const MetricDetailRow = ({ label, value }: MetricDetail) => {
const theme = useTheme(); const theme = useTheme();
return ( return (
<Stack <Stack
@@ -43,7 +52,7 @@ const MetricDetailRow = ({ label, value }: MetricDetailRowProps) => {
interface MetricItemProps { interface MetricItemProps {
label: string; label: string;
progress: number; progress: number;
details?: MetricDetailRowProps[]; details?: MetricDetail[];
} }
const MetricItem = ({ label, progress, details }: MetricItemProps) => { const MetricItem = ({ label, progress, details }: MetricItemProps) => {
@@ -75,8 +84,8 @@ const MetricItem = ({ label, progress, details }: MetricItemProps) => {
> >
<Gauge <Gauge
progress={progress} progress={progress}
radius={60} radius={GAUGE_RADIUS}
strokeWidth={12} strokeWidth={GAUGE_STROKE_WIDTH}
/> />
<Typography variant="body2">{label}</Typography> <Typography variant="body2">{label}</Typography>
</Box> </Box>
@@ -98,6 +107,92 @@ const MetricItem = ({ label, progress, details }: MetricItemProps) => {
); );
}; };
type LatestCheck = NonNullable<Monitor["recentChecks"]>[number];
const buildCpuMetric = (
check: LatestCheck,
t: (key: string) => string
): MetricConfig | null => {
if (!check.cpu || typeof check.cpu.usage_percent !== "number") {
return null;
}
const usagePercent = (check.cpu.usage_percent ?? 0) * PERCENTAGE_MULTIPLIER;
return {
key: "cpu",
label: t("pages.statusPages.monitorsList.infrastructure.cpu"),
hasData: true,
progress: usagePercent,
details: [
{
label: t("pages.statusPages.monitorsList.infrastructure.usage"),
value: `${usagePercent.toFixed(2)}%`,
},
],
};
};
const buildMemoryMetric = (
check: LatestCheck,
t: (key: string) => string
): MetricConfig | null => {
if (
!check.memory ||
typeof check.memory.usage_percent !== "number" ||
typeof check.memory.used_bytes !== "number" ||
typeof check.memory.total_bytes !== "number"
) {
return null;
}
return {
key: "memory",
label: t("pages.statusPages.monitorsList.infrastructure.memory"),
hasData: true,
progress: (check.memory.usage_percent ?? 0) * PERCENTAGE_MULTIPLIER,
details: [
{
label: t("pages.statusPages.monitorsList.infrastructure.used"),
value: prettyBytes(check.memory.used_bytes ?? 0),
},
{
label: t("pages.statusPages.monitorsList.infrastructure.total"),
value: prettyBytes(check.memory.total_bytes ?? 0),
},
],
};
};
const buildDiskMetric = (
check: LatestCheck,
t: (key: string) => string
): MetricConfig | null => {
if (!check.disk || check.disk.length === 0) {
return null;
}
const disks = check.disk;
const avgUsagePercent =
(disks.reduce((acc, disk) => acc + (disk?.usage_percent ?? 0), 0) / disks.length) *
PERCENTAGE_MULTIPLIER;
const totalUsedBytes = disks.reduce((acc, disk) => acc + (disk?.used_bytes ?? 0), 0);
const totalTotalBytes = disks.reduce((acc, disk) => acc + (disk?.total_bytes ?? 0), 0);
return {
key: "disk",
label: t("pages.statusPages.monitorsList.infrastructure.disk"),
hasData: true,
progress: avgUsagePercent,
details: [
{
label: t("pages.statusPages.monitorsList.infrastructure.used"),
value: prettyBytes(totalUsedBytes),
},
{
label: t("pages.statusPages.monitorsList.infrastructure.total"),
value: prettyBytes(totalTotalBytes),
},
],
};
};
export const InfrastructureMetrics = ({ monitor }: { monitor: StatusPageMonitor }) => { export const InfrastructureMetrics = ({ monitor }: { monitor: StatusPageMonitor }) => {
const theme = useTheme(); const theme = useTheme();
const { t } = useTranslation(); const { t } = useTranslation();
@@ -115,68 +210,22 @@ export const InfrastructureMetrics = ({ monitor }: { monitor: StatusPageMonitor
); );
} }
const metrics = [ const metrics: MetricConfig[] = [
{ buildCpuMetric(latestCheck, t),
key: t("pages.statusPages.monitorsList.infrastructure.cpu"), buildMemoryMetric(latestCheck, t),
labelKey: t("pages.statusPages.monitorsList.infrastructure.cpu"), buildDiskMetric(latestCheck, t),
hasData: latestCheck.cpu && typeof latestCheck.cpu.usage_percent === "number", ].filter((m): m is MetricConfig => m !== null);
progress: latestCheck.cpu?.usage_percent ? latestCheck.cpu.usage_percent * 100 : 0,
details: [ if (metrics.length === 0) {
{ return (
label: t("pages.statusPages.monitorsList.infrastructure.usage"), <Typography
value: `${((latestCheck.cpu?.usage_percent || 0) * 100).toFixed(2)}%`, variant="body2"
}, color={theme.palette.text.secondary}
], >
}, {t("pages.statusPages.monitorsList.noData")}
{ </Typography>
key: t("pages.statusPages.monitorsList.infrastructure.memoryText"), );
labelKey: t("pages.statusPages.monitorsList.infrastructure.memory"), }
hasData:
latestCheck.memory &&
typeof latestCheck.memory.usage_percent === "number" &&
typeof latestCheck.memory.used_bytes === "number" &&
typeof latestCheck.memory.total_bytes === "number",
progress: latestCheck.memory?.usage_percent
? latestCheck.memory.usage_percent * 100
: 0,
details: [
{
label: t("pages.statusPages.monitorsList.infrastructure.used"),
value: prettyBytes(latestCheck.memory?.used_bytes || 0),
},
{
label: t("pages.statusPages.monitorsList.infrastructure.total"),
value: prettyBytes(latestCheck.memory?.total_bytes || 0),
},
],
},
{
key: t("pages.statusPages.monitorsList.infrastructure.disk"),
labelKey: t("pages.statusPages.monitorsList.infrastructure.disk"),
hasData: latestCheck.disk && latestCheck.disk.length > 0,
progress: latestCheck.disk
? (latestCheck.disk.reduce((acc, disk) => acc + (disk?.usage_percent || 0), 0) /
latestCheck.disk.length) *
100
: 0,
details: [
{
label: t("pages.statusPages.monitorsList.infrastructure.used"),
value: prettyBytes(
latestCheck?.disk?.reduce((acc, disk) => acc + (disk?.used_bytes || 0), 0) ??
0
),
},
{
label: t("pages.statusPages.monitorsList.infrastructure.total"),
value: prettyBytes(
latestCheck?.disk?.reduce((acc, disk) => acc + (disk?.total_bytes || 0), 0) ??
0
),
},
],
},
];
return ( return (
<Grid <Grid
@@ -184,17 +233,14 @@ export const InfrastructureMetrics = ({ monitor }: { monitor: StatusPageMonitor
alignItems="center" alignItems="center"
padding={theme.spacing(LAYOUT.XS)} padding={theme.spacing(LAYOUT.XS)}
> >
{metrics.map( {metrics.map(({ key, label, progress, details }) => (
({ key, labelKey, hasData, progress, details }) => <MetricItem
hasData && ( key={key}
<MetricItem label={label}
key={key} progress={progress}
label={t(labelKey)} details={details}
progress={progress} />
details={details} ))}
/>
)
)}
</Grid> </Grid>
); );
}; };