diff --git a/server/src/config/services.ts b/server/src/config/services.ts index 06701491d..4437e9176 100644 --- a/server/src/config/services.ts +++ b/server/src/config/services.ts @@ -176,7 +176,7 @@ export const initializeServices = async ({ const bufferService = new BufferService({ logger, checkService, settingsService }); - const statusService = new StatusService({ db, logger, buffer: bufferService, monitorsRepository }); + const statusService = new StatusService({ logger, buffer: bufferService, monitorsRepository }); const webhookProvider = new WebhookProvider(logger); const slackProvider = new SlackProvider(logger); diff --git a/server/src/db/models/Monitor.ts b/server/src/db/models/Monitor.ts index 17565a2e4..0eeca0ed7 100644 --- a/server/src/db/models/Monitor.ts +++ b/server/src/db/models/Monitor.ts @@ -1,15 +1,18 @@ import { Schema, model, Types, type UpdateQuery } from "mongoose"; -import type { Monitor, MonitorMatchMethod, MonitorThresholds } from "@/types/monitor.js"; +import type { Monitor, MonitorMatchMethod, MonitorThresholds, CheckSnapshot } from "@/types/monitor.js"; import { MonitorTypes } from "@/types/monitor.js"; import Check from "./Check.js"; import MonitorStats from "./MonitorStats.js"; import StatusPage from "./StatusPage.js"; +type CheckSnapshotDocument = Omit & { createdAt: Date }; + type MonitorDocumentBase = Omit< Monitor, - "id" | "userId" | "teamId" | "notifications" | "selectedDisks" | "statusWindow" | "createdAt" | "updatedAt" + "id" | "userId" | "teamId" | "notifications" | "selectedDisks" | "statusWindow" | "recentChecks" | "createdAt" | "updatedAt" > & { statusWindow: boolean[]; + recentChecks: CheckSnapshotDocument[]; notifications: Types.ObjectId[]; selectedDisks: string[]; matchMethod?: MonitorMatchMethod; @@ -34,6 +37,15 @@ const thresholdsSchema = new Schema( { _id: false } ); +const checkSnapshotSchema = new Schema( + { + id: { type: String, required: true }, + status: { type: Boolean, required: true }, + createdAt: { type: Date, required: true }, + }, + { _id: false, strict: false } +); + const MonitorSchema = new Schema( { userId: { @@ -165,6 +177,10 @@ const MonitorSchema = new Schema( return value && value.trim() ? value.trim() : null; }, }, + recentChecks: { + type: [checkSnapshotSchema], + default: [], + }, }, { timestamps: true, diff --git a/server/src/repositories/monitors/MongoMonitorsRepository.ts b/server/src/repositories/monitors/MongoMonitorsRepository.ts index 5ce029634..9aeca380a 100644 --- a/server/src/repositories/monitors/MongoMonitorsRepository.ts +++ b/server/src/repositories/monitors/MongoMonitorsRepository.ts @@ -309,6 +309,7 @@ class MongoMonitorsRepository implements IMonitorsRepository { selectedDisks: doc.selectedDisks ?? [], gameId: doc.gameId ?? undefined, group: doc.group ?? null, + recentChecks: (doc.recentChecks ?? []).map((check: any) => ({ ...check, createdAt: check.createdAt instanceof Date ? check.createdAt.toISOString() : check.createdAt })), createdAt: toDateString(doc.createdAt), updatedAt: toDateString(doc.updatedAt), }; @@ -392,6 +393,7 @@ class MongoMonitorsRepository implements IMonitorsRepository { selectedDisks: doc.selectedDisks ?? [], gameId: doc.gameId ?? undefined, group: doc.group ?? null, + recentChecks: (doc.recentChecks ?? []).map((check: any) => ({ ...check, createdAt: check.createdAt instanceof Date ? check.createdAt.toISOString() : check.createdAt })), createdAt: toDateString(doc.createdAt), updatedAt: toDateString(doc.updatedAt), checks, diff --git a/server/src/service/business/checkService.ts b/server/src/service/business/checkService.ts index 42788eba8..bd4684f11 100644 --- a/server/src/service/business/checkService.ts +++ b/server/src/service/business/checkService.ts @@ -1,4 +1,5 @@ import { requireTeamId } from "@/controllers/controllerUtils.js"; +import { Types } from "mongoose"; import { IChecksRepository, IMonitorsRepository } from "@/repositories/index.js"; import type { MonitorType, MonitorStatusResponse, CheckErrorInfo, Check } from "@/types/index.js"; import type { HardwareStatusPayload, PageSpeedStatusPayload } from "@/types/network.js"; @@ -39,6 +40,8 @@ class CheckService { const { monitorId, teamId, type, status, responseTime, code, message, payload, timings } = statusResponse; const check: Partial = { + id: new Types.ObjectId().toString(), + createdAt: new Date().toISOString(), metadata: { monitorId, teamId, diff --git a/server/src/service/business/monitorService.ts b/server/src/service/business/monitorService.ts index 38fcaef78..90a909991 100644 --- a/server/src/service/business/monitorService.ts +++ b/server/src/service/business/monitorService.ts @@ -360,16 +360,12 @@ export class MonitorService implements IMonitorService { const snapshotOnlyRequest = requestedTypes.length > 0 && requestedTypes.every((requestedType) => snapshotTypes.includes(requestedType as MonitorType)); - const limitPerMonitor = snapshotOnlyRequest ? 1 : 25; - const checksMap = await this.checksRepository.findLatestByMonitorIds( - monitorsList.map((monitor) => monitor.id), - { limitPerMonitor } - ); - const monitorsWithChecks = monitorsList.map((monitor: Monitor) => { - const rawChecks = checksMap[monitor.id] ?? []; + const rawChecks = monitor.recentChecks ?? []; const isSnapshotType = snapshotOnlyRequest || snapshotTypes.includes(monitor.type); - const checks = isSnapshotType ? rawChecks.slice(0, 1) : NormalizeData(rawChecks, 10, 100); + // recentChecks are stored oldest-first, reverse to get newest-first for display + const reversedChecks = [...rawChecks].reverse(); + const checks = isSnapshotType ? reversedChecks.slice(0, 1) : NormalizeData(reversedChecks, 10, 100); return { ...monitor, checks, diff --git a/server/src/service/infrastructure/statusService.ts b/server/src/service/infrastructure/statusService.ts index 3a83dbd28..64b14d795 100755 --- a/server/src/service/infrastructure/statusService.ts +++ b/server/src/service/infrastructure/statusService.ts @@ -9,6 +9,7 @@ import type { Check, HardwareStatusPayload, PageSpeedStatusPayload, + CheckSnapshot, } from "@/types/index.js"; const SERVICE_NAME = "StatusService"; @@ -24,13 +25,11 @@ export interface IStatusService { export class StatusService implements IStatusService { static SERVICE_NAME = SERVICE_NAME; - private db: any; private logger: any; private buffer: any; private monitorsRepository: IMonitorsRepository; - constructor({ db, logger, buffer, monitorsRepository }: { db: any; logger: any; buffer: any; monitorsRepository: IMonitorsRepository }) { - this.db = db; + constructor({ logger, buffer, monitorsRepository }: { logger: any; buffer: any; monitorsRepository: IMonitorsRepository }) { this.logger = logger; this.buffer = buffer; this.monitorsRepository = monitorsRepository; @@ -175,14 +174,41 @@ export class StatusService implements IStatusService { // Update running stats this.updateRunningStats({ monitor, networkResponse: statusResponse }); - // If the status window size has changed, empty - monitor.statusWindow = monitor.statusWindow || []; monitor.statusWindow.push(status); while (monitor.statusWindow.length > monitor.statusWindowSize) { monitor.statusWindow.shift(); } + // Update recentChecks with check snapshot (excludes metadata, ack, expiry, __v, updatedAt) + const checkSnapshot: CheckSnapshot = { + id: check.id, + status: check.status, + responseTime: check.responseTime, + timings: check.timings, + statusCode: check.statusCode, + message: check.message, + cpu: check.cpu, + memory: check.memory, + disk: check.disk, + host: check.host, + errors: check.errors, + capture: check.capture, + net: check.net, + accessibility: check.accessibility, + bestPractices: check.bestPractices, + seo: check.seo, + performance: check.performance, + audits: check.audits, + createdAt: check.createdAt, + }; + monitor.recentChecks = monitor.recentChecks || []; + monitor.recentChecks.push(checkSnapshot); + const maxRecentChecks = 25; + while (monitor.recentChecks.length > maxRecentChecks) { + monitor.recentChecks.shift(); + } + if (monitor.status === undefined || monitor.status === null) { monitor.status = status; } diff --git a/server/src/types/check.ts b/server/src/types/check.ts index ee40ff6dc..6d38d538f 100644 --- a/server/src/types/check.ts +++ b/server/src/types/check.ts @@ -178,7 +178,11 @@ export interface ChecksSummary { cannotResolveChecks: number; } -export type NormalizedCheck = T & { +export interface HasResponseTime { + responseTime: number; +} + +export type NormalizedCheck = T & { originalResponseTime: number; }; diff --git a/server/src/types/monitor.ts b/server/src/types/monitor.ts index c7d99a88a..96cd44a65 100644 --- a/server/src/types/monitor.ts +++ b/server/src/types/monitor.ts @@ -1,4 +1,7 @@ import type { Check } from "@/types/check.js"; + +export type CheckSnapshot = Omit; + export const MonitorTypes = ["http", "ping", "pagespeed", "hardware", "docker", "port", "game", "unknown"] as const; export type MonitorType = (typeof MonitorTypes)[number]; @@ -42,6 +45,7 @@ export interface Monitor { selectedDisks: string[]; gameId?: string; group: string | null; + recentChecks: CheckSnapshot[]; createdAt: string; updatedAt: string; } @@ -54,7 +58,7 @@ export interface MonitorsSummary { } export interface MonitorWithChecks extends Monitor { - checks: Check[]; + checks: Check[] | CheckSnapshot[]; } export interface MonitorsWithChecksByTeamIdResult { diff --git a/server/src/utils/dataUtils.ts b/server/src/utils/dataUtils.ts index 0bf3e6416..b981365e9 100755 --- a/server/src/utils/dataUtils.ts +++ b/server/src/utils/dataUtils.ts @@ -1,6 +1,6 @@ -import type { Check, GroupedCheck, NormalizedCheck, NormalizedUptimeCheck } from "@/types/index.js"; +import type { GroupedCheck, NormalizedCheck, NormalizedUptimeCheck, HasResponseTime } from "@/types/index.js"; -const calculatePercentile = (arr: Check[], percentile: number): number => { +const calculatePercentile = (arr: T[], percentile: number): number => { const sorted = arr.slice().sort((a, b) => a.responseTime - b.responseTime); const index = (percentile / 100) * (sorted.length - 1); const lower = Math.floor(index); @@ -20,7 +20,7 @@ const calculatePercentileUptimeDetails = (arr: GroupedCheck[], percentile: numbe return sorted[lower]!.avgResponseTime * (1 - weight) + sorted[upper]!.avgResponseTime * weight; }; -export const NormalizeData = (checks: T[], rangeMin: number, rangeMax: number): NormalizedCheck[] => { +export const NormalizeData = (checks: T[], rangeMin: number, rangeMax: number): NormalizedCheck[] => { if (checks.length > 1) { const min = calculatePercentile(checks, 0); const max = calculatePercentile(checks, 95);