GroupedChecks
This commit is contained in:
1 parent
cdc58e5905
commit
3182141d0a
14 files changed
+592
-62
No files matched your search
@@ -33,6 +33,7 @@ export const XTick = ({ x, y, payload, range }: XTickProps) => {
|
||||
const format = tickDateFormatLookup(range);
|
||||
const theme = useTheme();
|
||||
const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
|
||||
console.log(payload);
|
||||
return (
|
||||
<Text
|
||||
x={x}
|
||||
@@ -124,7 +125,7 @@ export const ChartResponseTime = ({
|
||||
<XAxis
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
dataKey="_id"
|
||||
dataKey="bucketDate"
|
||||
tick={(props) => <XTick {...props} range={range} />}
|
||||
/>
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ import { Fragment, useId } from "react";
|
||||
import { XTick } from "./ChartResponseTime";
|
||||
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import type { IInfraCheck } from "@/types/check";
|
||||
import type { GroupedCheck } from "@/types/check";
|
||||
|
||||
const AREA_COLORS = [
|
||||
// Blues
|
||||
@@ -104,7 +104,7 @@ export const HistogramInfrastructure = ({
|
||||
title: string;
|
||||
type: string;
|
||||
idx: number | null;
|
||||
checks: IInfraCheck[];
|
||||
checks: GroupedCheck[];
|
||||
xKey: string;
|
||||
yDomain?: number[];
|
||||
dataKeys: string[];
|
||||
@@ -118,15 +118,15 @@ export const HistogramInfrastructure = ({
|
||||
const theme = useTheme();
|
||||
const uniqueId = useId();
|
||||
|
||||
let avgTemps: { _id: string; avg_temp: number | null }[] = [];
|
||||
let avgTemps: { bucketDate: Date; avg_temp: number | null }[] = [];
|
||||
let tempYDomain: number[] = [];
|
||||
if (type === "temp") {
|
||||
avgTemps = checks.map((check) => {
|
||||
const temps = check.cpu.temperature || [];
|
||||
const temps = check.cpu?.temperature || [];
|
||||
if (temps.length === 0) return { ...check, avg_temp: null };
|
||||
const totalTemp = temps.reduce((sum, temp) => sum + (temp || 0), 0);
|
||||
const avgTemp = totalTemp / temps.length;
|
||||
return { _id: check._id, avg_temp: avgTemp };
|
||||
return { bucketDate: check.bucketDate, avg_temp: avgTemp };
|
||||
});
|
||||
|
||||
const maxTemp: number = avgTemps.reduce((max, item) => {
|
||||
|
||||
@@ -64,7 +64,7 @@ export const HistogramPageSpeedScores = ({
|
||||
<ResponsiveContainer width="100%" minWidth={25} height={215}>
|
||||
<AreaChart data={checks}>
|
||||
<XAxis
|
||||
dataKey={"_id"}
|
||||
dataKey={"bucketDate"}
|
||||
tick={(props) => <XTick {...props} range={range} />}
|
||||
/>
|
||||
<CartesianGrid
|
||||
|
||||
@@ -43,7 +43,7 @@ const XLabel = ({
|
||||
fontSize={11}
|
||||
fill={theme.palette.text.secondary}
|
||||
>
|
||||
{formatDateWithTz(p1._id, dateFormat, uiTimezone)}
|
||||
{formatDateWithTz(p1.bucketDate, dateFormat, uiTimezone)}
|
||||
</text>
|
||||
<text
|
||||
x="100%"
|
||||
@@ -53,7 +53,7 @@ const XLabel = ({
|
||||
fontSize={11}
|
||||
fill={theme.palette.text.secondary}
|
||||
>
|
||||
{formatDateWithTz(p2._id, dateFormat, uiTimezone)}
|
||||
{formatDateWithTz(p2.bucketDate, dateFormat, uiTimezone)}
|
||||
</text>
|
||||
</>
|
||||
);
|
||||
@@ -91,8 +91,8 @@ export const HistogramStatus = ({
|
||||
const titleText = t("common.charts.uptime.avgResponseTime");
|
||||
const fmt = range === "30d" ? "MMM D, YYYY" : "ddd, MMM D, YYYY, h:mm A";
|
||||
let dateLabel = "";
|
||||
if (d?._id) {
|
||||
const base = new Date(d._id as any);
|
||||
if (d?.bucketDate) {
|
||||
const base = new Date(d.bucketDate);
|
||||
const midBucket =
|
||||
range === "30d" ? new Date(base.getTime() + 12 * 60 * 60 * 1000) : base;
|
||||
dateLabel = formatDateWithTz(midBucket.toISOString(), fmt, uiTimezone);
|
||||
@@ -174,7 +174,7 @@ export const HistogramStatus = ({
|
||||
);
|
||||
return (
|
||||
<Cell
|
||||
key={groupedCheck._id}
|
||||
key={groupedCheck.bucketDate}
|
||||
fill={theme.palette[fillColor].main}
|
||||
/>
|
||||
);
|
||||
|
||||
@@ -12,7 +12,6 @@ import { useTheme } from "@mui/material/styles";
|
||||
import { useParams } from "react-router";
|
||||
import type { ApiResponse } from "@/types/api";
|
||||
import type { IMonitor, IMonitorWithMonitorStats } from "@/types/monitor";
|
||||
import type { IInfraCheck } from "@/types/check";
|
||||
import {
|
||||
getFrequency,
|
||||
getCores,
|
||||
@@ -43,16 +42,16 @@ const InfraDetailsPage = () => {
|
||||
|
||||
const monitor = response?.data?.monitor;
|
||||
const stats = response?.data?.stats;
|
||||
const checks = (response?.data?.checks || []) as IInfraCheck[];
|
||||
const palette = getStatusPalette(monitor?.status || "initializing");
|
||||
const checks = Array.isArray(response?.data?.checks)
|
||||
? response?.data?.checks
|
||||
: [];
|
||||
const palette = getStatusPalette(monitor?.status ?? "initializing");
|
||||
|
||||
const streakDuration = stats?.currentStreakStartedAt
|
||||
? Date.now() - stats?.currentStreakStartedAt
|
||||
: 0;
|
||||
const streakStartedAt = stats?.currentStreakStartedAt ?? 0;
|
||||
const streakDuration = streakStartedAt > 0 ? Date.now() - streakStartedAt : 0;
|
||||
|
||||
const lastChecked = stats?.lastCheckTimestamp
|
||||
? Date.now() - stats?.lastCheckTimestamp
|
||||
: -1;
|
||||
const lastCheckTs = stats?.lastCheckTimestamp ?? -1;
|
||||
const lastChecked = lastCheckTs >= 0 ? Date.now() - lastCheckTs : -1;
|
||||
|
||||
if (!monitor) {
|
||||
return null;
|
||||
@@ -88,36 +87,38 @@ const InfraDetailsPage = () => {
|
||||
<StatBox
|
||||
title={t("monitors.common.stats.lastResponseTime")}
|
||||
subtitle={
|
||||
stats?.lastResponseTime ? `${stats?.lastResponseTime} ms` : "N/A"
|
||||
typeof stats?.lastResponseTime === "number"
|
||||
? `${stats.lastResponseTime} ms`
|
||||
: "N/A"
|
||||
}
|
||||
/>
|
||||
<StatBox
|
||||
title={t("monitors.common.stats.cpuPhysical")}
|
||||
subtitle={getCores(checks[0]?.cpu?.physical_core)}
|
||||
subtitle={getCores(checks?.[0]?.cpu?.physical_core || 0)}
|
||||
/>
|
||||
<StatBox
|
||||
title={t("monitors.common.stats.cpuLogical")}
|
||||
subtitle={getCores(checks[0]?.cpu?.logical_core)}
|
||||
subtitle={getCores(checks?.[0]?.cpu?.logical_core || 0)}
|
||||
/>
|
||||
<StatBox
|
||||
title={t("monitors.common.stats.cpuFrequency")}
|
||||
subtitle={getFrequency(checks[0]?.cpu?.current_frequency)}
|
||||
subtitle={getFrequency(checks?.[0]?.cpu?.current_frequency || 0)}
|
||||
/>
|
||||
<StatBox
|
||||
title={t("monitors.common.stats.cpuTemperature")}
|
||||
subtitle={getAvgTemp(checks[0]?.cpu?.temperature)}
|
||||
subtitle={getAvgTemp(checks?.[0]?.cpu?.temperature || [])}
|
||||
/>
|
||||
<StatBox
|
||||
title={t("monitors.common.stats.memory")}
|
||||
subtitle={getGbs(checks[0]?.memory?.total_bytes)}
|
||||
subtitle={getGbs(checks?.[0]?.memory?.total_bytes || 0)}
|
||||
/>
|
||||
<StatBox
|
||||
title={t("monitors.common.stats.disk")}
|
||||
subtitle={getDiskTotalGbs(checks[0]?.disk)}
|
||||
subtitle={getDiskTotalGbs(checks?.[0]?.disk)}
|
||||
/>
|
||||
<StatBox
|
||||
title={t("monitors.common.stats.os")}
|
||||
subtitle={getOsAndPlatform(checks[0]?.host)}
|
||||
subtitle={getOsAndPlatform(checks?.[0]?.host || {})}
|
||||
/>
|
||||
</Stack>
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@ import { Gauge } from "@/components/design-elements";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { getGbs, getFrequency } from "./InfraUtils";
|
||||
import type { IInfraCheck } from "@/types/check";
|
||||
import { useTheme } from "@mui/material/styles";
|
||||
import useMediaQuery from "@mui/material/useMediaQuery";
|
||||
import type { GroupedCheck } from "@/types/check";
|
||||
|
||||
const InfraDetailGauge = ({
|
||||
title,
|
||||
@@ -42,7 +42,7 @@ const InfraDetailGauge = ({
|
||||
);
|
||||
};
|
||||
|
||||
export const InfraDetailsGauges = ({ checks }: { checks: IInfraCheck[] }) => {
|
||||
export const InfraDetailsGauges = ({ checks }: { checks: GroupedCheck[] }) => {
|
||||
const { t } = useTranslation();
|
||||
const theme = useTheme();
|
||||
const isSmall = useMediaQuery(theme.breakpoints.down("md"));
|
||||
@@ -54,31 +54,31 @@ export const InfraDetailsGauges = ({ checks }: { checks: IInfraCheck[] }) => {
|
||||
>
|
||||
<InfraDetailGauge
|
||||
title={t("monitors.infrastructure.gauges.memory.title")}
|
||||
progress={(checks[0]?.memory.usage_percent || 0) * 100}
|
||||
progress={(checks[0]?.memory?.usage_percent || 0) * 100}
|
||||
upperLabel={t("monitors.infrastructure.gauges.memory.upperLabel")}
|
||||
upperValue={getGbs(checks[0]?.memory.used_bytes)}
|
||||
upperValue={getGbs(checks[0]?.memory?.used_bytes || 0)}
|
||||
lowerLabel={t("monitors.infrastructure.gauges.memory.lowerLabel")}
|
||||
lowerValue={getGbs(checks[0]?.memory.total_bytes)}
|
||||
lowerValue={getGbs(checks[0]?.memory?.total_bytes || 0)}
|
||||
/>
|
||||
<InfraDetailGauge
|
||||
title={t("monitors.infrastructure.gauges.cpu.title")}
|
||||
progress={(checks[0]?.cpu.usage_percent || 0) * 100}
|
||||
progress={(checks[0]?.cpu?.usage_percent || 0) * 100}
|
||||
upperLabel={t("monitors.infrastructure.gauges.cpu.upperLabel")}
|
||||
upperValue={getFrequency(checks[0]?.cpu.current_frequency)}
|
||||
upperValue={getFrequency(checks[0]?.cpu?.current_frequency || 0)}
|
||||
lowerLabel={t("monitors.infrastructure.gauges.cpu.lowerLabel")}
|
||||
lowerValue={getFrequency(checks[0]?.cpu.frequency)}
|
||||
lowerValue={getFrequency(checks[0]?.cpu?.frequency || 0)}
|
||||
/>
|
||||
{checks[0]?.disk?.map((disk, idx) => {
|
||||
return (
|
||||
<InfraDetailGauge
|
||||
key={disk.device + idx}
|
||||
key={disk?.device || 0 + idx}
|
||||
// title={`Disk ${idx} usage`}
|
||||
title={t("monitors.infrastructure.gauges.disk.title", { idx })}
|
||||
progress={(disk.usage_percent || 0) * 100}
|
||||
upperLabel={t("monitors.infrastructure.gauges.disk.upperLabel")}
|
||||
upperValue={getGbs(disk.used_bytes)}
|
||||
upperValue={getGbs(disk?.used_bytes || 0)}
|
||||
lowerLabel={t("monitors.infrastructure.gauges.disk.lowerLabel")}
|
||||
lowerValue={getGbs(disk.total_bytes)}
|
||||
lowerValue={getGbs(disk?.total_bytes || 0)}
|
||||
/>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -2,12 +2,12 @@ import Grid from "@mui/material/Grid";
|
||||
import { HistogramInfrastructure } from "@/components/monitors";
|
||||
|
||||
import { useTranslation } from "react-i18next";
|
||||
import type { IInfraCheck } from "@/types/check";
|
||||
import type { GroupedCheck } 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[], t: any) => {
|
||||
const getChartConfigs = (theme: any, checks: GroupedCheck[], t: any) => {
|
||||
return [
|
||||
{
|
||||
title: t("common.charts.infrastructure.memory.title"),
|
||||
@@ -52,7 +52,7 @@ export const InfraDetailsGraphs = ({
|
||||
checks,
|
||||
range,
|
||||
}: {
|
||||
checks: IInfraCheck[];
|
||||
checks: GroupedCheck[];
|
||||
range: string;
|
||||
}) => {
|
||||
const theme = useTheme();
|
||||
|
||||
@@ -36,7 +36,10 @@ export const getGbs = (bytes: number): string => {
|
||||
}
|
||||
};
|
||||
|
||||
export const getDiskTotalGbs = (disk: IDiskInfo[]): string => {
|
||||
export const getDiskTotalGbs = (disk?: Partial<IDiskInfo>[]): string => {
|
||||
if (!disk) {
|
||||
return getGbs(0);
|
||||
}
|
||||
const totalBytes =
|
||||
disk?.reduce((acc, disk) => acc + (disk.total_bytes || 0), 0) || 0;
|
||||
return getGbs(totalBytes);
|
||||
|
||||
@@ -146,16 +146,32 @@ export interface CheckWithMonitor {
|
||||
updatedAt: string;
|
||||
timings: CheckTimings;
|
||||
}
|
||||
|
||||
export interface GroupedCheck {
|
||||
_id: string;
|
||||
avgResponseTime: number;
|
||||
count: number;
|
||||
upChecks?: number;
|
||||
downChecks?: number;
|
||||
avgResponseTimeUp?: number | null;
|
||||
avgResponseTimeDown?: number | null;
|
||||
runningContainersSnapshot?: IDockerContainerSummary[];
|
||||
bucketDate: Date;
|
||||
|
||||
count?: number;
|
||||
avgResponseTime?: number;
|
||||
|
||||
totalContainers?: number;
|
||||
runningContainers?: number;
|
||||
healthyContainers?: number;
|
||||
|
||||
accessibility?: number | null;
|
||||
bestPractices?: number | null;
|
||||
seo?: number | null;
|
||||
performance?: number | null;
|
||||
cls?: number | null;
|
||||
si?: number | null;
|
||||
fcp?: number | null;
|
||||
lcp?: number | null;
|
||||
tbt?: number | null;
|
||||
|
||||
// Infrastructure aggregates (optional snapshot/averages)
|
||||
cpu?: Partial<ICpuInfo>;
|
||||
memory?: Partial<IMemoryInfo>;
|
||||
disk?: Partial<IDiskInfo>[];
|
||||
host?: Partial<IHostInfo>;
|
||||
net?: Array<Pick<INetInfo, "name" | "bytes_recv" | "bytes_sent">>;
|
||||
}
|
||||
|
||||
export interface LatestCheck {
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import type { CheckEntity } from "@/types/domain/index.js";
|
||||
import type {
|
||||
AggregateCheck,
|
||||
CheckEntity,
|
||||
Monitor,
|
||||
} from "@/types/domain/index.js";
|
||||
import type { LatestChecksByMonitor } from "@/repositories/checks/MongoCheckRepository.js";
|
||||
export interface IChecksRepository {
|
||||
// Create
|
||||
@@ -7,6 +11,10 @@ export interface IChecksRepository {
|
||||
findLatestChecksByMonitorIds(
|
||||
monitorIds: string[]
|
||||
): Promise<LatestChecksByMonitor>;
|
||||
findRecentChecksByMonitor(
|
||||
monitor: Monitor,
|
||||
startDate: Date
|
||||
): Promise<AggregateCheck[]>;
|
||||
// Update
|
||||
// Delete
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { IChecksRepository } from "@/repositories/index.js";
|
||||
import { CheckEntity } from "@/types/domain/check.js";
|
||||
import { CheckEntity, AggregateCheck, Monitor } from "@/types/domain/index.js";
|
||||
import type { ICheck } from "@/db/models/index.js";
|
||||
import { Check } from "@/db/models/index.js";
|
||||
import mongoose from "mongoose";
|
||||
@@ -36,6 +36,357 @@ class MongoCheckRepository implements IChecksRepository {
|
||||
return entity;
|
||||
};
|
||||
|
||||
private toAggregateCheck = (doc: any): AggregateCheck => {
|
||||
const agg: AggregateCheck = {
|
||||
bucketDate: doc._id instanceof Date ? doc._id : new Date(doc._id),
|
||||
count: doc.count,
|
||||
avgResponseTime: doc.avgResponseTime,
|
||||
totalContainers: doc.totalContainers,
|
||||
runningContainers: doc.runningContainers,
|
||||
healthyContainers: doc.healthyContainers,
|
||||
accessibility: doc.accessibility,
|
||||
bestPractices: doc.bestPractices,
|
||||
seo: doc.seo,
|
||||
performance: doc.performance,
|
||||
cls: doc.cls,
|
||||
si: doc.si,
|
||||
fcp: doc.fcp,
|
||||
lcp: doc.lcp,
|
||||
tbt: doc.tbt,
|
||||
};
|
||||
|
||||
if (doc.cpu || doc.memory || doc.disk || doc.host || doc.net) {
|
||||
if (doc.cpu) agg.cpu = doc.cpu;
|
||||
if (doc.memory) agg.memory = doc.memory;
|
||||
if (Array.isArray(doc.disk)) agg.disk = doc.disk;
|
||||
if (doc.host) agg.host = doc.host;
|
||||
if (Array.isArray(doc.net)) agg.net = doc.net;
|
||||
}
|
||||
return agg;
|
||||
};
|
||||
|
||||
private getBaseGroup = (): Record<string, any> => {
|
||||
return {
|
||||
_id: { $dateTrunc: { date: "$createdAt", unit: "minute" } },
|
||||
count: { $sum: 1 },
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
};
|
||||
};
|
||||
|
||||
private getBaseProjection = (): object => {
|
||||
return { status: 1, responseTime: 1, createdAt: 1 };
|
||||
};
|
||||
|
||||
private getPageSpeedGroup = (): Record<string, any> => {
|
||||
return {
|
||||
_id: { $dateTrunc: { date: "$createdAt", unit: "minute" } },
|
||||
count: { $sum: 1 },
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
accessibility: { $avg: "$lighthouse.accessibility" },
|
||||
bestPractices: { $avg: "$lighthouse.bestPractices" },
|
||||
seo: { $avg: "$lighthouse.seo" },
|
||||
performance: { $avg: "$lighthouse.performance" },
|
||||
cls: { $avg: "$lighthouse.audits.cls.score" },
|
||||
si: { $avg: "$lighthouse.audits.si.score" },
|
||||
fcp: { $avg: "$lighthouse.audits.fcp.score" },
|
||||
lcp: { $avg: "$lighthouse.audits.lcp.score" },
|
||||
tbt: { $avg: "$lighthouse.audits.tbt.score" },
|
||||
};
|
||||
};
|
||||
|
||||
private getPageSpeedProjection = (): object => {
|
||||
const projectStage: any = { status: 1, responseTime: 1, createdAt: 1 };
|
||||
projectStage["lighthouse.accessibility"] = 1;
|
||||
projectStage["lighthouse.seo"] = 1;
|
||||
projectStage["lighthouse.bestPractices"] = 1;
|
||||
projectStage["lighthouse.performance"] = 1;
|
||||
projectStage["lighthouse.audits.cls.score"] = 1;
|
||||
projectStage["lighthouse.audits.si.score"] = 1;
|
||||
projectStage["lighthouse.audits.fcp.score"] = 1;
|
||||
projectStage["lighthouse.audits.lcp.score"] = 1;
|
||||
projectStage["lighthouse.audits.tbt.score"] = 1;
|
||||
return projectStage;
|
||||
};
|
||||
|
||||
private getInfraGroup = (): Record<string, any> => {
|
||||
return {
|
||||
_id: { $dateTrunc: { date: "$createdAt", unit: "minute" } },
|
||||
count: { $sum: 1 },
|
||||
avgResponseTime: { $avg: "$responseTime" },
|
||||
physicalCores: { $last: "$system.cpu.physical_core" },
|
||||
logicalCores: { $last: "$system.cpu.logical_core" },
|
||||
frequency: { $avg: "$system.cpu.frequency" },
|
||||
currentFrequency: { $last: "$system.cpu.current_frequency" },
|
||||
tempsArrays: { $push: "$system.cpu.temperature" },
|
||||
freePercent: { $avg: "$system.cpu.free_percent" },
|
||||
usedPercent: { $avg: "$system.cpu.usage_percent" },
|
||||
total_bytes: { $last: "$system.memory.total_bytes" },
|
||||
available_bytes: { $last: "$system.memory.available_bytes" },
|
||||
used_bytes: { $last: "$system.memory.used_bytes" },
|
||||
memory_usage_percent: { $avg: "$system.memory.usage_percent" },
|
||||
disksArray: { $push: "$system.disk" },
|
||||
os: { $last: "$system.host.os" },
|
||||
platform: { $last: "$system.host.platform" },
|
||||
kernel_version: { $last: "$system.host.kernel_version" },
|
||||
pretty_name: { $last: "$system.host.pretty_name" },
|
||||
netsArray: { $push: "$system.net" },
|
||||
};
|
||||
};
|
||||
|
||||
private getInfraProjection = (): object => {
|
||||
const projectStage: any = { status: 1, responseTime: 1, createdAt: 1 };
|
||||
projectStage["system.cpu.physical_core"] = 1;
|
||||
projectStage["system.cpu.logical_core"] = 1;
|
||||
projectStage["system.cpu.frequency"] = 1;
|
||||
projectStage["system.cpu.current_frequency"] = 1;
|
||||
projectStage["system.cpu.temperature"] = 1;
|
||||
projectStage["system.cpu.free_percent"] = 1;
|
||||
projectStage["system.cpu.usage_percent"] = 1;
|
||||
projectStage["system.memory.total_bytes"] = 1;
|
||||
projectStage["system.memory.available_bytes"] = 1;
|
||||
projectStage["system.memory.used_bytes"] = 1;
|
||||
projectStage["system.memory.usage_percent"] = 1;
|
||||
projectStage["system.disk"] = 1;
|
||||
projectStage["system.host.os"] = 1;
|
||||
projectStage["system.host.platform"] = 1;
|
||||
projectStage["system.host.kernel_version"] = 1;
|
||||
projectStage["system.host.pretty_name"] = 1;
|
||||
projectStage["system.net"] = 1;
|
||||
return projectStage;
|
||||
};
|
||||
|
||||
private getDockerGroup = (): Record<string, any> => {
|
||||
return {
|
||||
_id: { $dateTrunc: { date: "$createdAt", unit: "minute" } },
|
||||
count: { $sum: 1 },
|
||||
avgResponseTime: { $last: "$responseTime" },
|
||||
totalContainers: {
|
||||
$last: { $size: { $ifNull: ["$dockerContainers", []] } },
|
||||
},
|
||||
runningContainers: {
|
||||
$last: {
|
||||
$size: {
|
||||
$filter: {
|
||||
input: { $ifNull: ["$dockerContainers", []] },
|
||||
as: "c",
|
||||
cond: { $eq: ["$$c.running", true] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
healthyContainers: {
|
||||
$last: {
|
||||
$size: {
|
||||
$filter: {
|
||||
input: { $ifNull: ["$dockerContainers", []] },
|
||||
as: "c",
|
||||
cond: { $eq: ["$$c.health.healthy", true] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
private getDockerProjection = (): object => {
|
||||
const projectStage: any = { status: 1, responseTime: 1, createdAt: 1 };
|
||||
projectStage["dockerContainers"] = 1;
|
||||
return projectStage;
|
||||
};
|
||||
|
||||
private getFinalProjection = (type: string): object => {
|
||||
if (type === "pagespeed") {
|
||||
return {
|
||||
_id: 1,
|
||||
count: 1,
|
||||
avgResponseTime: 1,
|
||||
accessibility: "$accessibility",
|
||||
seo: "$seo",
|
||||
bestPractices: "$bestPractices",
|
||||
performance: "$performance",
|
||||
cls: "$cls",
|
||||
si: "$si",
|
||||
fcp: "$fcp",
|
||||
lcp: "$lcp",
|
||||
tbt: "$tbt",
|
||||
};
|
||||
}
|
||||
|
||||
if (type === "infrastructure") {
|
||||
return {
|
||||
_id: 1,
|
||||
count: 1,
|
||||
avgResponseTime: 1,
|
||||
cpu: {
|
||||
physical_core: "$physicalCores",
|
||||
logical_core: "$logicalCores",
|
||||
frequency: "$frequency",
|
||||
current_frequency: "$currentFrequency",
|
||||
temperature: {
|
||||
$map: {
|
||||
input: {
|
||||
$range: [
|
||||
0,
|
||||
{
|
||||
$size: {
|
||||
$ifNull: [{ $arrayElemAt: ["$tempsArrays", 0] }, []],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
as: "idx",
|
||||
in: {
|
||||
$avg: {
|
||||
$map: {
|
||||
input: { $ifNull: ["$tempsArrays", []] },
|
||||
as: "arr",
|
||||
in: { $arrayElemAt: ["$$arr", "$$idx"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
free_percent: "$freePercent",
|
||||
used_percent: "$usedPercent",
|
||||
},
|
||||
memory: {
|
||||
total_bytes: "$total_bytes",
|
||||
available_bytes: "$available_bytes",
|
||||
used_bytes: "$used_bytes",
|
||||
usage_percent: "$memory_usage_percent",
|
||||
},
|
||||
disk: {
|
||||
$map: {
|
||||
input: {
|
||||
$range: [
|
||||
0,
|
||||
{
|
||||
$size: {
|
||||
$ifNull: [{ $arrayElemAt: ["$disksArray", 0] }, []],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
as: "idx",
|
||||
in: {
|
||||
$let: {
|
||||
vars: {
|
||||
diskGroup: {
|
||||
$map: {
|
||||
input: { $ifNull: ["$disksArray", []] },
|
||||
as: "diskArr",
|
||||
in: { $arrayElemAt: ["$$diskArr", "$$idx"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
in: {
|
||||
device: { $arrayElemAt: ["$$diskGroup.device", 0] },
|
||||
total_bytes: { $avg: "$$diskGroup.total_bytes" },
|
||||
free_bytes: { $avg: "$$diskGroup.free_bytes" },
|
||||
used_bytes: { $avg: "$$diskGroup.used_bytes" },
|
||||
usage_percent: { $avg: "$$diskGroup.usage_percent" },
|
||||
total_inodes: { $avg: "$$diskGroup.total_inodes" },
|
||||
free_inodes: { $avg: "$$diskGroup.free_inodes" },
|
||||
used_inodes: { $avg: "$$diskGroup.used_inodes" },
|
||||
inodes_usage_percent: {
|
||||
$avg: "$$diskGroup.inodes_usage_percent",
|
||||
},
|
||||
read_bytes: { $avg: "$$diskGroup.read_bytes" },
|
||||
write_bytes: { $avg: "$$diskGroup.write_bytes" },
|
||||
read_time: { $avg: "$$diskGroup.read_time" },
|
||||
write_time: { $avg: "$$diskGroup.write_time" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
host: {
|
||||
os: "$os",
|
||||
platform: "$platform",
|
||||
kernel_version: "$kernel_version",
|
||||
pretty_name: "$pretty_name",
|
||||
},
|
||||
net: {
|
||||
$map: {
|
||||
input: {
|
||||
$range: [
|
||||
0,
|
||||
{
|
||||
$size: { $ifNull: [{ $arrayElemAt: ["$netsArray", 0] }, []] },
|
||||
},
|
||||
],
|
||||
},
|
||||
as: "idx",
|
||||
in: {
|
||||
$let: {
|
||||
vars: {
|
||||
netGroup: {
|
||||
$map: {
|
||||
input: { $ifNull: ["$netsArray", []] },
|
||||
as: "netArr",
|
||||
in: { $arrayElemAt: ["$$netArr", "$$idx"] },
|
||||
},
|
||||
},
|
||||
},
|
||||
in: {
|
||||
name: { $arrayElemAt: ["$$netGroup.name", 0] },
|
||||
bytes_sent: { $avg: "$$netGroup.bytes_sent" },
|
||||
bytes_recv: { $avg: "$$netGroup.bytes_recv" },
|
||||
packets_sent: { $avg: "$$netGroup.packets_sent" },
|
||||
packets_recv: { $avg: "$$netGroup.packets_recv" },
|
||||
err_in: { $avg: "$$netGroup.err_in" },
|
||||
err_out: { $avg: "$$netGroup.err_out" },
|
||||
drop_in: { $avg: "$$netGroup.drop_in" },
|
||||
drop_out: { $avg: "$$netGroup.drop_out" },
|
||||
fifo_in: { $avg: "$$netGroup.fifo_in" },
|
||||
fifo_out: { $avg: "$$netGroup.fifo_out" },
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
if (type === "docker") {
|
||||
return {
|
||||
_id: 1,
|
||||
count: 1,
|
||||
avgResponseTime: 1,
|
||||
totalContainers: "$totalContainers",
|
||||
runningContainers: "$runningContainers",
|
||||
healthyContainers: "$healthyContainers",
|
||||
runningContainersSnapshot: "$runningContainersSnapshot",
|
||||
totalExposedPorts: "$totalExposedPorts",
|
||||
uniqueImages: "$uniqueImages",
|
||||
runningPercent: {
|
||||
$cond: [
|
||||
{ $gt: ["$totalContainers", 0] },
|
||||
{
|
||||
$multiply: [
|
||||
{ $divide: ["$runningContainers", "$totalContainers"] },
|
||||
100,
|
||||
],
|
||||
},
|
||||
null,
|
||||
],
|
||||
},
|
||||
healthyPercent: {
|
||||
$cond: [
|
||||
{ $gt: ["$totalContainers", 0] },
|
||||
{
|
||||
$multiply: [
|
||||
{ $divide: ["$healthyContainers", "$totalContainers"] },
|
||||
100,
|
||||
],
|
||||
},
|
||||
null,
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
return {};
|
||||
};
|
||||
|
||||
findLatestChecksByMonitorIds = async (monitorIds: string[]) => {
|
||||
const mongoIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
|
||||
const checkMap = await Check.aggregate([
|
||||
@@ -58,9 +409,110 @@ class MongoCheckRepository implements IChecksRepository {
|
||||
},
|
||||
]);
|
||||
return checkMap.map((cm) => {
|
||||
return { id: cm._id, latestChecks: cm.latestChecks };
|
||||
return {
|
||||
id: cm._id,
|
||||
latestChecks: cm.latestChecks.map((c: ICheck) => this.toEntity(c)),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
findRecentChecksByMonitor = async (monitor: Monitor, startDate: Date) => {
|
||||
const endDate = new Date();
|
||||
const matchStage: {
|
||||
"metadata.monitorId": mongoose.Types.ObjectId;
|
||||
createdAt: { $gte: Date; $lt: Date };
|
||||
} = {
|
||||
"metadata.monitorId": new mongoose.Types.ObjectId(monitor.id),
|
||||
createdAt: { $gte: startDate, $lt: endDate },
|
||||
};
|
||||
|
||||
let groupClause;
|
||||
if (monitor.type === "pagespeed") {
|
||||
groupClause = this.getPageSpeedGroup();
|
||||
} else if (monitor.type === "infrastructure") {
|
||||
groupClause = this.getInfraGroup();
|
||||
} else if (monitor.type === "docker") {
|
||||
groupClause = this.getDockerGroup();
|
||||
} else {
|
||||
groupClause = this.getBaseGroup();
|
||||
}
|
||||
|
||||
let projectStage;
|
||||
if (monitor.type === "pagespeed") {
|
||||
projectStage = this.getPageSpeedProjection();
|
||||
} else if (monitor.type === "infrastructure") {
|
||||
projectStage = this.getInfraProjection();
|
||||
} else if (monitor.type === "docker") {
|
||||
projectStage = this.getDockerProjection();
|
||||
} else {
|
||||
projectStage = this.getBaseProjection();
|
||||
}
|
||||
|
||||
let finalProjection = {};
|
||||
if (
|
||||
monitor.type === "pagespeed" ||
|
||||
monitor.type === "infrastructure" ||
|
||||
monitor.type === "docker"
|
||||
) {
|
||||
finalProjection = this.getFinalProjection(monitor.type);
|
||||
} else {
|
||||
finalProjection = { _id: 1, count: 1, avgResponseTime: 1 };
|
||||
}
|
||||
|
||||
const pipeline: any[] = [
|
||||
{ $match: matchStage },
|
||||
{ $project: { ...projectStage, status: 1 } },
|
||||
];
|
||||
|
||||
// For infrastructure and docker monitors we rely on $last in group, which requires ordering by createdAt
|
||||
if (monitor.type === "infrastructure" || monitor.type === "docker") {
|
||||
pipeline.push({ $sort: { createdAt: 1 } });
|
||||
}
|
||||
|
||||
pipeline.push(
|
||||
{
|
||||
$group: {
|
||||
...groupClause,
|
||||
upChecks: { $sum: { $cond: [{ $eq: ["$status", "up"] }, 1, 0] } },
|
||||
downChecks: { $sum: { $cond: [{ $eq: ["$status", "down"] }, 1, 0] } },
|
||||
sumResponseUp: {
|
||||
$sum: { $cond: [{ $eq: ["$status", "up"] }, "$responseTime", 0] },
|
||||
},
|
||||
sumResponseDown: {
|
||||
$sum: { $cond: [{ $eq: ["$status", "down"] }, "$responseTime", 0] },
|
||||
},
|
||||
},
|
||||
},
|
||||
{ $sort: { _id: -1 } },
|
||||
{
|
||||
$project: {
|
||||
...finalProjection,
|
||||
upChecks: 1,
|
||||
downChecks: 1,
|
||||
avgResponseTimeUp: {
|
||||
$cond: [
|
||||
{ $gt: ["$upChecks", 0] },
|
||||
{ $divide: ["$sumResponseUp", "$upChecks"] },
|
||||
null,
|
||||
],
|
||||
},
|
||||
avgResponseTimeDown: {
|
||||
$cond: [
|
||||
{ $gt: ["$downChecks", 0] },
|
||||
{ $divide: ["$sumResponseDown", "$downChecks"] },
|
||||
null,
|
||||
],
|
||||
},
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const checks = await Check.aggregate(pipeline)
|
||||
.allowDiskUse(true)
|
||||
.hint({ "metadata.monitorId": 1, createdAt: 1 });
|
||||
|
||||
return checks.map(this.toAggregateCheck);
|
||||
};
|
||||
}
|
||||
|
||||
export default MongoCheckRepository;
|
||||
@@ -707,7 +707,25 @@ class MonitorService implements IMonitorService {
|
||||
if (range === "24h" || range === "7d" || range === "30d") {
|
||||
return await this.getChecksOtherRanges(monitor, range, startDate);
|
||||
} else {
|
||||
return await this.getChecksRecent(monitor, startDate);
|
||||
const checks = await this.checksRepository.findRecentChecksByMonitor(
|
||||
monitor,
|
||||
startDate
|
||||
);
|
||||
|
||||
const stats = await MonitorStats.findOne({
|
||||
monitorId: monitor.id,
|
||||
});
|
||||
|
||||
if (!stats) {
|
||||
throw new ApiError("Monitor stats not found", 404);
|
||||
}
|
||||
|
||||
return {
|
||||
checks,
|
||||
monitor,
|
||||
stats,
|
||||
};
|
||||
// return await this.getChecksRecent(monitor, startDate);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -135,3 +135,37 @@ export interface CheckEntity {
|
||||
updatedAt: Date;
|
||||
expiry: Date;
|
||||
}
|
||||
|
||||
// AggregateCheck reflects the minimal shape needed from aggregation results
|
||||
// for list/history views, with string ids and optional docker payload.
|
||||
export interface AggregateCheck {
|
||||
// Time bucket identifier from aggregation (_id)
|
||||
bucketDate: Date;
|
||||
|
||||
// Common aggregates
|
||||
count?: number;
|
||||
avgResponseTime?: number;
|
||||
|
||||
// Docker aggregates (counts per bucket)
|
||||
totalContainers?: number;
|
||||
runningContainers?: number;
|
||||
healthyContainers?: number;
|
||||
|
||||
// PageSpeed aggregates
|
||||
accessibility?: number | null;
|
||||
bestPractices?: number | null;
|
||||
seo?: number | null;
|
||||
performance?: number | null;
|
||||
cls?: number | null;
|
||||
si?: number | null;
|
||||
fcp?: number | null;
|
||||
lcp?: number | null;
|
||||
tbt?: number | null;
|
||||
|
||||
// Infrastructure aggregates (optional snapshot/averages)
|
||||
cpu?: Partial<ICpuInfo>;
|
||||
memory?: Partial<IMemoryInfo>;
|
||||
disk?: Partial<IDiskInfo>[];
|
||||
host?: Partial<IHostInfo>;
|
||||
net?: Array<Pick<INetInfo, "name" | "bytes_recv" | "bytes_sent">>;
|
||||
}
|
||||
@@ -1,11 +1,8 @@
|
||||
import { IMonitorStats } from "@/db/models/index.js";
|
||||
import type { Monitor } from "@/types/domain/index.js";
|
||||
import type { AggregateCheck } from "@/types/domain/index.js";
|
||||
export interface MonitorWithChecksResponse {
|
||||
monitor: Monitor;
|
||||
checks: Array<{
|
||||
_id: string;
|
||||
count: number;
|
||||
avgResponseTime: number;
|
||||
}>;
|
||||
checks: Array<AggregateCheck>;
|
||||
stats: IMonitorStats;
|
||||
}
|
||||
Reference in new issue
Block a user