From 3182141d0a5699ec7bab10593932d5ef42afba92 Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Mon, 5 Jan 2026 04:17:11 +0000 Subject: [PATCH] GroupedChecks --- .../components/monitors/ChartResponseTime.tsx | 3 +- .../monitors/HistogramInfrastructure.tsx | 10 +- .../monitors/HistogramPageSpeedScores.tsx | 2 +- .../components/monitors/HistogramStatus.tsx | 10 +- .../src/pages/infrastructure/InfraDetails.tsx | 35 +- .../infrastructure/InfraDetailsGauges.tsx | 22 +- .../infrastructure/InfraDetailsGraphs.tsx | 6 +- client/src/pages/infrastructure/InfraUtils.ts | 5 +- client/src/types/check.ts | 34 +- .../repositories/checks/IChecksRepository.ts | 10 +- .../checks/MongoCheckRepository.ts | 456 +++++++++++++++++- .../src/services/business/MonitorService.ts | 20 +- server/src/types/domain/check.ts | 34 ++ .../src/types/monitor-response-with-checks.ts | 7 +- 14 files changed, 592 insertions(+), 62 deletions(-) diff --git a/client/src/components/monitors/ChartResponseTime.tsx b/client/src/components/monitors/ChartResponseTime.tsx index 12ee5252f..6f1416c3b 100644 --- a/client/src/components/monitors/ChartResponseTime.tsx +++ b/client/src/components/monitors/ChartResponseTime.tsx @@ -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 ( } /> diff --git a/client/src/components/monitors/HistogramInfrastructure.tsx b/client/src/components/monitors/HistogramInfrastructure.tsx index c109ca0f5..0a57a660c 100644 --- a/client/src/components/monitors/HistogramInfrastructure.tsx +++ b/client/src/components/monitors/HistogramInfrastructure.tsx @@ -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) => { diff --git a/client/src/components/monitors/HistogramPageSpeedScores.tsx b/client/src/components/monitors/HistogramPageSpeedScores.tsx index 8e8d410de..2b4138cc8 100644 --- a/client/src/components/monitors/HistogramPageSpeedScores.tsx +++ b/client/src/components/monitors/HistogramPageSpeedScores.tsx @@ -64,7 +64,7 @@ export const HistogramPageSpeedScores = ({ } /> - {formatDateWithTz(p1._id, dateFormat, uiTimezone)} + {formatDateWithTz(p1.bucketDate, dateFormat, uiTimezone)} - {formatDateWithTz(p2._id, dateFormat, uiTimezone)} + {formatDateWithTz(p2.bucketDate, dateFormat, uiTimezone)} ); @@ -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 ( ); diff --git a/client/src/pages/infrastructure/InfraDetails.tsx b/client/src/pages/infrastructure/InfraDetails.tsx index 9a194f0d0..4b896bb05 100644 --- a/client/src/pages/infrastructure/InfraDetails.tsx +++ b/client/src/pages/infrastructure/InfraDetails.tsx @@ -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 = () => { diff --git a/client/src/pages/infrastructure/InfraDetailsGauges.tsx b/client/src/pages/infrastructure/InfraDetailsGauges.tsx index 1daecea06..781fe2f15 100644 --- a/client/src/pages/infrastructure/InfraDetailsGauges.tsx +++ b/client/src/pages/infrastructure/InfraDetailsGauges.tsx @@ -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[] }) => { > {checks[0]?.disk?.map((disk, idx) => { return ( ); })} diff --git a/client/src/pages/infrastructure/InfraDetailsGraphs.tsx b/client/src/pages/infrastructure/InfraDetailsGraphs.tsx index 15661e6ba..ea46aa42c 100644 --- a/client/src/pages/infrastructure/InfraDetailsGraphs.tsx +++ b/client/src/pages/infrastructure/InfraDetailsGraphs.tsx @@ -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(); diff --git a/client/src/pages/infrastructure/InfraUtils.ts b/client/src/pages/infrastructure/InfraUtils.ts index 20f06c43c..be5103f29 100644 --- a/client/src/pages/infrastructure/InfraUtils.ts +++ b/client/src/pages/infrastructure/InfraUtils.ts @@ -36,7 +36,10 @@ export const getGbs = (bytes: number): string => { } }; -export const getDiskTotalGbs = (disk: IDiskInfo[]): string => { +export const getDiskTotalGbs = (disk?: Partial[]): string => { + if (!disk) { + return getGbs(0); + } const totalBytes = disk?.reduce((acc, disk) => acc + (disk.total_bytes || 0), 0) || 0; return getGbs(totalBytes); diff --git a/client/src/types/check.ts b/client/src/types/check.ts index afa7812fa..951b0b835 100644 --- a/client/src/types/check.ts +++ b/client/src/types/check.ts @@ -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; + memory?: Partial; + disk?: Partial[]; + host?: Partial; + net?: Array>; } export interface LatestCheck { diff --git a/server/src/repositories/checks/IChecksRepository.ts b/server/src/repositories/checks/IChecksRepository.ts index ced2e5a51..ea5cd0399 100644 --- a/server/src/repositories/checks/IChecksRepository.ts +++ b/server/src/repositories/checks/IChecksRepository.ts @@ -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; + findRecentChecksByMonitor( + monitor: Monitor, + startDate: Date + ): Promise; // Update // Delete } diff --git a/server/src/repositories/checks/MongoCheckRepository.ts b/server/src/repositories/checks/MongoCheckRepository.ts index 02f2eb9b1..f454058cf 100644 --- a/server/src/repositories/checks/MongoCheckRepository.ts +++ b/server/src/repositories/checks/MongoCheckRepository.ts @@ -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 => { + 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 => { + 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 => { + 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 => { + 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; diff --git a/server/src/services/business/MonitorService.ts b/server/src/services/business/MonitorService.ts index f28271fb5..71ba6004a 100644 --- a/server/src/services/business/MonitorService.ts +++ b/server/src/services/business/MonitorService.ts @@ -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); } }; diff --git a/server/src/types/domain/check.ts b/server/src/types/domain/check.ts index da3e6867e..5b3e829ce 100644 --- a/server/src/types/domain/check.ts +++ b/server/src/types/domain/check.ts @@ -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; + memory?: Partial; + disk?: Partial[]; + host?: Partial; + net?: Array>; +} diff --git a/server/src/types/monitor-response-with-checks.ts b/server/src/types/monitor-response-with-checks.ts index f9e064e44..27c1da64f 100644 --- a/server/src/types/monitor-response-with-checks.ts +++ b/server/src/types/monitor-response-with-checks.ts @@ -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; stats: IMonitorStats; }