From 51081a6a0ebee8f7f9ca7af0e520fce308b66c6b Mon Sep 17 00:00:00 2001 From: Alex Holliday Date: Tue, 6 Jan 2026 20:49:06 +0000 Subject: [PATCH] incidents repo and data reversal --- .../components/checks/CardCheckDetails.tsx | 8 +- client/src/components/checks/ChartTiming.tsx | 4 +- .../components/common/HeatmapResponseTime.tsx | 17 +- .../common/HeatmapResponseTimeTooltip.tsx | 8 +- .../common/HistogramResponseTime.tsx | 6 +- .../components/monitors/BarDockerCount.tsx | 2 +- .../monitors/HistogramDockerPercentage.tsx | 2 +- .../monitors/HistogramInfrastructure.tsx | 5 +- client/src/pages/checks/CheckDetails.tsx | 4 +- client/src/pages/checks/ChecksPage.tsx | 5 +- client/src/pages/checks/ChecksTable.tsx | 21 +- .../src/pages/incidents/IncidentDetails.tsx | 14 +- client/src/pages/incidents/IncidentTable.tsx | 16 +- client/src/pages/incidents/IncidentsPage.tsx | 4 +- client/src/types/check.ts | 48 ++-- client/src/types/incident.ts | 30 ++- server/src/db/models/incidents/Incident.ts | 7 +- server/src/db/models/index.ts | 4 +- server/src/init/services.ts | 4 +- .../incidents/IIncidentsRepository.ts | 49 ++++ .../incidents/MongoIncidentsRepository.ts | 192 +++++++++++++++ server/src/repositories/index.ts | 3 + .../src/services/business/IncidentService.ts | 226 ++++++++---------- .../infrastructure/NotificationService.ts | 11 +- .../NotificationServices/Discord.ts | 6 +- .../NotificationServices/Email.ts | 6 +- .../NotificationServices/IMessageService.ts | 12 +- .../NotificationServices/Slack.ts | 6 +- .../NotificationServices/Webhook.ts | 6 +- server/src/types/domain/incident.ts | 28 +++ server/src/types/domain/index.ts | 1 + server/src/validation/incidents.ts | 23 +- 32 files changed, 537 insertions(+), 241 deletions(-) create mode 100644 server/src/repositories/incidents/IIncidentsRepository.ts create mode 100644 server/src/repositories/incidents/MongoIncidentsRepository.ts create mode 100644 server/src/types/domain/incident.ts diff --git a/client/src/components/checks/CardCheckDetails.tsx b/client/src/components/checks/CardCheckDetails.tsx index b926574d0..c8110eb66 100644 --- a/client/src/components/checks/CardCheckDetails.tsx +++ b/client/src/components/checks/CardCheckDetails.tsx @@ -8,7 +8,7 @@ import { StatusLabel, ValueLabel } from "@/components/design-elements"; import { BaseBox } from "@/components/design-elements"; import { useAppSelector } from "@/hooks/AppHooks"; -import type { ICheck } from "@/types/check"; +import type { Check } from "@/types/check"; import type { MonitorStatus } from "@/types/monitor"; import { formatDateWithTz } from "@/utils/TimeUtils"; import { useTheme } from "@mui/material/styles"; @@ -16,7 +16,7 @@ import { getMonitorPath } from "@/utils/MonitorUtils"; import { useTranslation } from "react-i18next"; type CheckDetailsCardProps = { - check: ICheck; + check: Check; }; export const CheckDetailsCard = ({ check }: CheckDetailsCardProps) => { @@ -50,7 +50,7 @@ export const CheckDetailsCard = ({ check }: CheckDetailsCardProps) => { const httpText = Number.isFinite(httpStatusCode) ? String(httpStatusCode) : "-"; - const typeText = check?.metadata?.type ?? "-"; + const typeText = check?.type ?? "-"; const checkedAtText = check?.createdAt ? formatDateWithTz(check.createdAt, "ddd, MMM D, YYYY, HH:mm A", uiTimezone) : "-"; @@ -71,7 +71,7 @@ export const CheckDetailsCard = ({ check }: CheckDetailsCardProps) => { })} {(() => { - const href = `/${getMonitorPath(check.metadata.type)}/${check.metadata.monitorId}`; + const href = `/${getMonitorPath(check.type)}/${check.monitorId}`; return href ? ( (); - if (!checks || checks.length === 0) { - checks = []; - } - if (checks.length !== 25) { - const placeholders = Array(25 - checks.length).fill({ - status: "placeholder", + const latestChecks = checks.slice(-25).reverse(); + + let data: Array; + if (latestChecks.length !== 25) { + const placeholders = Array(25 - latestChecks.length).fill({ + status: "placeholder" as const, }); - data = [...checks, ...placeholders]; + data = [...latestChecks, ...placeholders]; } else { - data = checks; + data = latestChecks; } return ( diff --git a/client/src/components/common/HeatmapResponseTimeTooltip.tsx b/client/src/components/common/HeatmapResponseTimeTooltip.tsx index 3244b1aa5..062e0b96e 100644 --- a/client/src/components/common/HeatmapResponseTimeTooltip.tsx +++ b/client/src/components/common/HeatmapResponseTimeTooltip.tsx @@ -3,15 +3,17 @@ import Tooltip from "@mui/material/Tooltip"; import Typography from "@mui/material/Typography"; import { formatDateWithTz } from "@/utils/TimeUtils"; import { useAppSelector } from "@/hooks/AppHooks"; -import type { LatestCheck } from "@/types/check"; +import type { Check } from "@/types/check"; import { useTheme } from "@mui/material/styles"; +type HeatmapCheck = Check | { status: "placeholder" }; + export const HeatmapResponseTimeTooltip = ({ children, check, }: { children: React.ReactElement; - check: LatestCheck; + check: HeatmapCheck; }) => { const uiTimezone = useAppSelector((state: any) => state.ui.timezone); const theme = useTheme(); @@ -47,7 +49,7 @@ export const HeatmapResponseTimeTooltip = ({ > {formatDateWithTz( - check?.checkedAt, + check?.createdAt, "ddd, MMMM D, YYYY, HH:mm A", uiTimezone )} diff --git a/client/src/components/common/HistogramResponseTime.tsx b/client/src/components/common/HistogramResponseTime.tsx index 9c1d48176..660c32dac 100644 --- a/client/src/components/common/HistogramResponseTime.tsx +++ b/client/src/components/common/HistogramResponseTime.tsx @@ -22,7 +22,10 @@ export const HistogramResponseTime = ({ if (!Array.isArray(checks) || checks.length === 0) return null; - const normalized = normalizeResponseTimes(checks.slice(-25), "responseTime"); + const normalized = normalizeResponseTimes( + checks.slice(-25).reverse(), + "responseTime" + ); let data = Array(); if (!normalized || normalized.length === 0) { @@ -36,7 +39,6 @@ export const HistogramResponseTime = ({ } else { data = normalized; } - const chartHeight = typeof height === "number" ? `${height}px` : height; const gridGap = gap ?? theme.spacing(0.5); diff --git a/client/src/components/monitors/BarDockerCount.tsx b/client/src/components/monitors/BarDockerCount.tsx index 5a0f39ae4..cfd2f0d59 100644 --- a/client/src/components/monitors/BarDockerCount.tsx +++ b/client/src/components/monitors/BarDockerCount.tsx @@ -66,7 +66,7 @@ export const BarDockerCount = ({ ) : ( diff --git a/client/src/components/monitors/HistogramDockerPercentage.tsx b/client/src/components/monitors/HistogramDockerPercentage.tsx index 167355b9c..de0eea61b 100644 --- a/client/src/components/monitors/HistogramDockerPercentage.tsx +++ b/client/src/components/monitors/HistogramDockerPercentage.tsx @@ -62,7 +62,7 @@ export const HistogramDockerPercentage = ({ ) : ( { const theme = useTheme(); const uniqueId = useId(); + let data = checks.reverse(); let avgTemps: { bucketDate: string; avg_temp: number | null }[] = []; let tempYDomain: number[] = []; if (type === "temp") { - avgTemps = checks.map((check) => { + avgTemps = data.map((check) => { const temps = check.cpu?.temperature || []; if (temps.length === 0) return { ...check, avg_temp: null }; const totalTemp = temps.reduce((sum, temp) => sum + (temp || 0), 0); @@ -139,7 +140,7 @@ export const HistogramInfrastructure = ({ return ( - + } diff --git a/client/src/pages/checks/CheckDetails.tsx b/client/src/pages/checks/CheckDetails.tsx index 86e9f51bc..0003d4ee7 100644 --- a/client/src/pages/checks/CheckDetails.tsx +++ b/client/src/pages/checks/CheckDetails.tsx @@ -4,12 +4,12 @@ import Grid from "@mui/material/Grid"; import { useParams } from "react-router"; import { useGet } from "@/hooks/UseApi"; -import type { ICheck } from "@/types/check"; +import type { Check } from "@/types/check"; import type { ApiResponse } from "@/types/api"; const CheckDetails = () => { const { id } = useParams(); - const { response, loading, error } = useGet>( + const { response, loading, error } = useGet>( `/checks/${id}` ); diff --git a/client/src/pages/checks/ChecksPage.tsx b/client/src/pages/checks/ChecksPage.tsx index 022456bb8..f6522bdfd 100644 --- a/client/src/pages/checks/ChecksPage.tsx +++ b/client/src/pages/checks/ChecksPage.tsx @@ -12,7 +12,7 @@ import type { SelectChangeEvent } from "@mui/material/Select"; import { useGet } from "@/hooks/UseApi"; import type { ApiResponse } from "@/types/api"; import type { IMonitor } from "@/types/monitor"; -import type { ICheck } from "@/types/check"; +import type { Check } from "@/types/check"; import { config } from "@/config/index"; const ChecksPage = () => { @@ -29,7 +29,7 @@ const ChecksPage = () => { const monitors: IMonitor[] = monitorResponse?.data || []; const { response: checksResponse, loading: checksLoading } = useGet< - ApiResponse<{ hasMore: boolean; checks: ICheck[] }> + ApiResponse<{ hasMore: boolean; checks: Check[] }> >( `/checks?page=${page}&rowsPerPage=${rowsPerPage}&range=${range}&status=${status}${ selectedMonitorId !== "all" ? `&monitorId=${selectedMonitorId}` : "" @@ -101,6 +101,7 @@ const ChecksPage = () => { void; @@ -38,12 +37,15 @@ export const ChecksTable = ({ const navigate = useNavigate(); const getHeaders = (t: Function, uiTimezone: string) => { - const headers: Header[] = [ + const headers: Header[] = [ { id: "monitorName", content: t("common.table.headers.monitor"), render: (row) => { - return row.metadata?.monitorId?.name || "N/A"; + return ( + monitors?.find((monitor) => monitor.id === row.monitorId)?.name || + "N/A" + ); }, }, { @@ -69,6 +71,7 @@ export const ChecksTable = ({ content: t("checks.table.headers.statusCode"), render: (row) => { const code = row.httpStatusCode; + if (!code) return "N/A"; const value = code < 300 ? "positive" : code < 400 ? "neutral" : "negative"; return ; @@ -108,7 +111,7 @@ export const ChecksTable = ({ headers={headers} data={checks} onRowClick={(row) => { - navigate(`/checks/${row._id}`); + navigate(`/checks/${row.id}`); }} emptyViewText={t("checks.table.empty")} /> diff --git a/client/src/pages/incidents/IncidentDetails.tsx b/client/src/pages/incidents/IncidentDetails.tsx index cea3b47fc..ec484ea40 100644 --- a/client/src/pages/incidents/IncidentDetails.tsx +++ b/client/src/pages/incidents/IncidentDetails.tsx @@ -7,7 +7,7 @@ import { useTheme } from "@mui/material/styles"; import { useNavigate, useParams } from "react-router"; import { useGet } from "@/hooks/UseApi"; import type { ApiResponse } from "@/types/api"; -import type { IIncident } from "@/types/incident"; +import type { IncidentWithDetails } from "@/types/incident"; import { formatDateWithTz } from "@/utils/TimeUtils"; import { useAppSelector } from "@/hooks/AppHooks"; import prettyMilliseconds from "pretty-ms"; @@ -22,7 +22,9 @@ const IncidentDetailsPage = () => { const uiTimezone = useAppSelector((state: any) => state.ui.timezone); const navigate = useNavigate(); - const { response } = useGet>(`/incidents/${id}`); + const { response } = useGet>( + `/incidents/${id}` + ); const incident = response?.data || null; if (!incident) { @@ -45,11 +47,11 @@ const IncidentDetailsPage = () => { { - const type = incident.monitorId.type as MonitorType; + const type = incident.monitor.type; const path = getMonitorPath(type); - const id = (incident.monitorId as any)?._id; + const id = incident.monitor?.id; if (id) navigate(`/${path}/${id}`); }} /> @@ -78,7 +80,7 @@ const IncidentDetailsPage = () => { void; @@ -39,12 +39,12 @@ export const IncidentTable = ({ const navigate = useNavigate(); const getHeaders = (t: Function, uiTimezone: string) => { - const headers: Header[] = [ + const headers: Header[] = [ { id: "name", content: t("common.table.headers.monitor"), render: (row) => { - return row.monitorId?.name || "N/A"; + return row.monitor?.name || "N/A"; }, }, { @@ -75,7 +75,7 @@ export const IncidentTable = ({ id: "status", content: t("incidents.table.headers.monitorStatus"), render: (row) => { - const status = row.monitorId?.status; + const status = row.monitor?.status; return status ? ( ) : ( @@ -106,7 +106,7 @@ export const IncidentTable = ({ id: "resolvedBy", content: t("incidents.table.headers.resolvedBy"), render: (row) => { - return row.resolvedBy?.email || "N/A"; + return row.resolvedByUser?.email || "N/A"; }, }, { @@ -118,7 +118,7 @@ export const IncidentTable = ({ loading={isPatching} onClick={async (e) => { e.stopPropagation(); - await patch(`/incidents/${row._id}/resolve`, { + await patch(`/incidents/${row.id}/resolve`, { resolutionNote: "Resolved via UI", }); refetch(); @@ -158,7 +158,7 @@ export const IncidentTable = ({ headers={headers} data={incidents} onRowClick={(row) => { - navigate(`/incidents/${row._id}`); + navigate(`/incidents/${row.id}`); }} emptyViewPositive emptyViewText={t("incidents.table.empty")} diff --git a/client/src/pages/incidents/IncidentsPage.tsx b/client/src/pages/incidents/IncidentsPage.tsx index a3b9dcdba..73a6cc176 100644 --- a/client/src/pages/incidents/IncidentsPage.tsx +++ b/client/src/pages/incidents/IncidentsPage.tsx @@ -12,7 +12,7 @@ import { useState, useEffect } from "react"; import { useGet } from "@/hooks/UseApi"; import type { ApiResponse } from "@/types/api"; import type { SelectChangeEvent } from "@mui/material/Select"; -import type { IIncident } from "@/types/incident"; +import type { IncidentWithDetails } from "@/types/incident"; import type { IMonitor } from "@/types/monitor"; import { config } from "@/config/index"; @@ -31,7 +31,7 @@ const IncidentsPage = () => { loading: incidentsLoading, isValidating: incidentsValidating, refetch, - } = useGet>( + } = useGet>( `/incidents?page=${page}&rowsPerPage=${rowsPerPage}&range=${range}${ selectedMonitorId && selectedMonitorId !== "all" ? `&monitorId=${selectedMonitorId}` diff --git a/client/src/types/check.ts b/client/src/types/check.ts index 283bce0a3..7ceac80b4 100644 --- a/client/src/types/check.ts +++ b/client/src/types/check.ts @@ -1,4 +1,4 @@ -import type { MonitorType } from "./monitor"; +import type { MonitorType, MonitorStatus } from "./monitor"; export interface CheckTimingPhases { wait: number; @@ -11,7 +11,7 @@ export interface CheckTimingPhases { total: number; } -export interface CheckTimings { +export interface GotTimings { start: string; socket: string; lookup: string; @@ -103,6 +103,12 @@ export interface INetInfo { fifo_in: number; fifo_out: number; } + +export interface ICaptureInfo { + version?: string; + mode?: string; +} + export interface ICheck { _id: string; metadata: { @@ -119,33 +125,35 @@ export interface ICheck { expiry: string; createdAt: string; updatedAt: string; - timings: CheckTimings; + timings: GotTimings; lighthouse?: ICheckLighthouseFields; system?: ISystemInfo; // Present for docker monitor checks dockerContainers?: IDockerContainerSummary[]; } -export interface CheckWithMonitor { - _id: string; - metadata: { - monitorId: { - _id: string; - name: string; - }; - type: string; - teamId: string; - }; - status: string; + +export interface Check { + id: string; + monitorId: string; + teamId: string; + type: MonitorType; + status: MonitorStatus; + httpStatusCode?: number; message: string; - responseTime: number; - normalResponseTime?: number; - httpStatusCode: number; - ack: boolean; - expiry: string; + responseTime?: number; + timings?: GotTimings; + errorMessage?: string; + ackAt?: string; + ackBy?: string; + system?: ISystemInfo; + capture?: ICaptureInfo; + lighthouse?: ICheckLighthouseFields; + dockerContainers?: IDockerContainerSummary[]; createdAt: string; updatedAt: string; - timings: CheckTimings; + expiry: string; } + export interface AggregateCheck { bucketDate: string; diff --git a/client/src/types/incident.ts b/client/src/types/incident.ts index 4c77510b1..2a6009144 100644 --- a/client/src/types/incident.ts +++ b/client/src/types/incident.ts @@ -1,16 +1,28 @@ -import type { IMongoUser } from "@/types/user"; -import type { IMonitor } from "@/types/monitor"; - -export interface IIncident { - _id: string; - monitorId: IMonitor; +export const ResolutionTypes = ["auto", "manual"] as const; +export type ResolutionType = (typeof ResolutionTypes)[number]; +import type { MonitorType, MonitorStatus } from "@/types/monitor"; +export interface Incident { + id: string; + monitorId: string; teamId: string; startedAt: string; startCheck: string; - resolved: boolean; endedAt?: string; endCheck?: string; - resolvedBy?: IMongoUser; - resolutionType?: string; + resolved: boolean; + resolvedBy?: string; + resolutionType?: ResolutionType; resolutionNote?: string; } + +export interface IncidentWithDetails extends Incident { + monitor: { + id: string; + name: string; + type: MonitorType; + status: MonitorStatus; + }; + resolvedByUser?: { + email: string; + }; +} diff --git a/server/src/db/models/incidents/Incident.ts b/server/src/db/models/incidents/Incident.ts index aa4ef25f1..f46e21108 100644 --- a/server/src/db/models/incidents/Incident.ts +++ b/server/src/db/models/incidents/Incident.ts @@ -1,7 +1,6 @@ -import mongoose, { Schema, Document, Types } from "mongoose"; - -export const ResolutionTypes = ["auto", "manual"] as const; -export type ResolutionType = (typeof ResolutionTypes)[number]; +import mongoose, { Schema, Types } from "mongoose"; +import type { ResolutionType } from "@/types/domain/index.js"; +import { ResolutionTypes } from "@/types/domain/index.js"; export interface IIncident { _id: Types.ObjectId; diff --git a/server/src/db/models/index.ts b/server/src/db/models/index.ts index e64d92fa7..7659a4099 100644 --- a/server/src/db/models/index.ts +++ b/server/src/db/models/index.ts @@ -48,8 +48,8 @@ export type { IStatusPage } from "./status-page/StatusPage.js"; export { RecoveryToken } from "./recovery/RecoveryToken.js"; export type { IRecoveryToken } from "./recovery/RecoveryToken.js"; -export { Incident, ResolutionTypes } from "./incidents/Incident.js"; -export type { IIncident, ResolutionType } from "./incidents/Incident.js"; +export { Incident } from "./incidents/Incident.js"; +export type { IIncident } from "./incidents/Incident.js"; export { SystemSettings } from "./system/SystemSettings.js"; export type { ISystemSettings } from "./system/SystemSettings.js"; diff --git a/server/src/init/services.ts b/server/src/init/services.ts index fb53e0df8..a8c756c0a 100644 --- a/server/src/init/services.ts +++ b/server/src/init/services.ts @@ -37,6 +37,7 @@ import { MongoMonitorRepository, MongoChecksRepository, MongoMonitorStatsRepository, + MongoIncidentsRepository, } from "@/repositories/index.js"; import type { CheckEntity } from "@/types/domain/index.js"; @@ -44,6 +45,7 @@ export const initServices = async () => { const monitorRepository = new MongoMonitorRepository(); const checksRepository = new MongoChecksRepository(); const monitorStatsRepository = new MongoMonitorStatsRepository(); + const incidentsRepository = new MongoIncidentsRepository(); const checkService = new CheckService(checksRepository, monitorRepository); const inviteService = new InviteService(); @@ -72,7 +74,7 @@ export const initServices = async () => { userService, settingsService ); - const incidentService = new IncidentService(); + const incidentService = new IncidentService(incidentsRepository); const statsAggregationService = new StatsAggregationService(); const jobGenerator = new JobGenerator( networkService, diff --git a/server/src/repositories/incidents/IIncidentsRepository.ts b/server/src/repositories/incidents/IIncidentsRepository.ts new file mode 100644 index 000000000..c8e136c11 --- /dev/null +++ b/server/src/repositories/incidents/IIncidentsRepository.ts @@ -0,0 +1,49 @@ +import type { + Incident as IncidentEntity, + IncidentWithDetails, + ResolutionType, +} from "@/types/domain/index.js"; + +export interface IIncidentsRepository { + // create + create(incident: Partial): Promise; + // single fetch + findByMonitorIdAndResolved( + monitorId: string, + teamId: string, + resolved: boolean + ): Promise; + findByIdWithMonitorAndResolvedBy( + incidentId: string, + teamId: string + ): Promise; + // collection fetch + count( + teamId: string, + startDate: Date, + monitorId?: string, + resolved?: boolean, + resolutionType?: ResolutionType + ): Promise; + findAllWithMonitorAndResolvedBy( + teamId: string, + page: number, + rowsPerPage: number, + startDate: Date, + monitorId?: string, + resolved?: boolean, + resolutionType?: ResolutionType + ): Promise; + + findAllByTeamId(teamId: string): Promise; + // update + updateById( + incidentId: string, + teamId: string, + updates: Partial + ): Promise; + // delete + deleteById(incidentId: string, teamId: string): Promise; +} + +export default IIncidentsRepository; diff --git a/server/src/repositories/incidents/MongoIncidentsRepository.ts b/server/src/repositories/incidents/MongoIncidentsRepository.ts new file mode 100644 index 000000000..d5f44bb93 --- /dev/null +++ b/server/src/repositories/incidents/MongoIncidentsRepository.ts @@ -0,0 +1,192 @@ +import mongoose from "mongoose"; +import type { IIncidentsRepository } from "./IIncidentsRepository.js"; +import type { + Incident as IncidentEntity, + IncidentWithDetails, + ResolutionType, +} from "@/types/domain/index.js"; +import type { IIncident, IMonitor, IUser } from "@/db/models/index.js"; +import { Incident } from "@/db/models/index.js"; + +type IncidentPopulated = Omit & { + monitorId: IMonitor; + resolvedBy?: IUser | null; +}; + +class MongoIncidentsRepository implements IIncidentsRepository { + private toEntity = (doc: IIncident): IncidentEntity => { + return { + id: doc._id.toString(), + monitorId: doc.monitorId.toString(), + teamId: doc.teamId.toString(), + startedAt: doc.startedAt, + startCheck: doc.startCheck.toString(), + endedAt: doc.endedAt, + endCheck: doc.endCheck?.toString(), + resolved: doc.resolved, + resolvedBy: doc.resolvedBy?.toString(), + resolutionType: doc.resolutionType, + resolutionNote: doc.resolutionNote, + }; + }; + + private toEntityWithDetails = ( + doc: IncidentPopulated + ): IncidentWithDetails => { + return { + id: doc._id.toString(), + monitorId: "", + teamId: doc.teamId.toString(), + startedAt: doc.startedAt, + startCheck: doc.startCheck.toString(), + endedAt: doc.endedAt, + endCheck: doc.endCheck?.toString(), + resolved: doc.resolved, + resolutionType: doc.resolutionType, + resolutionNote: doc.resolutionNote, + monitor: { + id: doc.monitorId._id.toString(), + name: doc.monitorId.name, + type: doc.monitorId.type, + status: doc.monitorId.status, + }, + resolvedByUser: doc.resolvedBy + ? { + email: doc.resolvedBy.email, + } + : undefined, + }; + }; + + create = async (incidentData: Partial) => { + const existing = await Incident.findOne({ + monitorId: incidentData.monitorId, + teamId: incidentData.teamId, + resolved: false, + }); + + if (existing) { + return this.toEntity(existing); + } + + const { teamId, monitorId, startCheck } = incidentData; + + const incident = await Incident.create({ + monitorId: new mongoose.Types.ObjectId(monitorId), + teamId: new mongoose.Types.ObjectId(teamId), + startedAt: new Date(), + startCheck: new mongoose.Types.ObjectId(startCheck), + }); + + return this.toEntity(incident); + }; + + findByMonitorIdAndResolved = async ( + monitorId: string, + teamId: string, + resolved: boolean + ) => { + const incident = await Incident.findOne({ + monitorId: monitorId, + teamId: teamId, + resolved: resolved, + }); + + if (!incident) return null; + + return this.toEntity(incident); + }; + + findByIdWithMonitorAndResolvedBy = async ( + incidentId: string, + teamId: string + ) => { + const incident = await Incident.findOne({ + _id: new mongoose.Types.ObjectId(incidentId), + teamId: new mongoose.Types.ObjectId(teamId), + }) + .populate("monitorId") + .populate("resolvedBy") + .lean(); + if (!incident) return null; + return this.toEntityWithDetails(incident); + }; + + count = async ( + teamId: string, + startDate: Date, + monitorId?: string, + resolved?: boolean, + resolutionType?: ResolutionType + ) => { + const count = await Incident.countDocuments({ + teamId: teamId, + ...(monitorId && { monitorId }), + createdAt: { $gte: startDate }, + ...(resolved !== undefined && { resolved }), + ...(resolutionType !== undefined && { resolutionType }), + }); + return count; + }; + + findAllWithMonitorAndResolvedBy = async ( + teamId: string, + page: number, + rowsPerPage: number, + startDate: Date, + monitorId?: string, + resolved?: boolean, + resolutionType?: ResolutionType + ) => { + const match = { + teamId: teamId, + ...(monitorId && { monitorId }), + createdAt: { $gte: startDate }, + ...(resolved !== undefined && { resolved }), + ...(resolutionType !== undefined && { resolutionType }), + }; + const incidents = await Incident.find(match) + .populate("monitorId") + .populate("resolvedBy") + .sort({ createdAt: -1 }) + .skip(page * rowsPerPage) + .limit(rowsPerPage) + .lean(); + return incidents.map((incident) => this.toEntityWithDetails(incident)); + }; + + findAllByTeamId = async (teamId: string) => { + const incidents = await Incident.find({ + teamId, + }) + .populate("monitorId") + .populate("resolvedBy") + .lean(); + return incidents.map((incident) => this.toEntityWithDetails(incident)); + }; + + updateById = async ( + incidentId: string, + teamId: string, + updates: Partial + ) => { + const updatedIncident = await Incident.findOneAndUpdate( + { _id: incidentId, teamId, resolved: false }, + { + $set: updates, + }, + { new: true } + ); + return this.toEntity(updatedIncident!); + }; + + deleteById = async (incidentId: string, teamId: string) => { + const result = await Incident.deleteOne({ + _id: new mongoose.Types.ObjectId(incidentId), + teamId: new mongoose.Types.ObjectId(teamId), + }); + return result.deletedCount === 1; + }; +} + +export default MongoIncidentsRepository; diff --git a/server/src/repositories/index.ts b/server/src/repositories/index.ts index 804721628..d9f57caeb 100644 --- a/server/src/repositories/index.ts +++ b/server/src/repositories/index.ts @@ -9,3 +9,6 @@ export { default as MongoChecksRepository } from "@/repositories/checks/MongoChe export type { IMonitorStatsRepository } from "@/repositories/monitor-stats/IMonitorStatsRepository.js"; export { default as MongoMonitorStatsRepository } from "@/repositories/monitor-stats/MongoMonitorStatsRepository.js"; + +export type { IIncidentsRepository } from "@/repositories/incidents/IIncidentsRepository.js"; +export { default as MongoIncidentsRepository } from "@/repositories/incidents/MongoIncidentsRepository.js"; diff --git a/server/src/services/business/IncidentService.ts b/server/src/services/business/IncidentService.ts index c35d7a194..a68d7cc17 100644 --- a/server/src/services/business/IncidentService.ts +++ b/server/src/services/business/IncidentService.ts @@ -5,37 +5,37 @@ import { Monitor, IUser, } from "@/db/models/index.js"; -import type { ResolutionType } from "@/db/models/index.js"; -import mongoose from "mongoose"; +import type { ResolutionType } from "@/types/domain/index.js"; import { getChildLogger } from "@/logger/Logger.js"; import { ThresholdEvaluationResult } from "@/services/infrastructure/StatusService.js"; import { getStartDate } from "@/utils/TimeUtils.js"; import type { Monitor as MonitorEntity, CheckEntity, + Incident as IncidentEntity, + IncidentWithDetails, } from "@/types/domain/index.js"; - -type IncidentPopulated = Omit & { - monitorId: IMonitor; - resolvedBy?: IUser | null; -}; +import type { IIncidentsRepository } from "@/repositories/index.js"; export interface IIncidentService { handleStatusChange: ( updatedMonitor: MonitorEntity, lastCheck: CheckEntity - ) => Promise; + ) => Promise; handleThresholdBreach: ( updatedMonitor: MonitorEntity, lastCheck: CheckEntity, evalResult: ThresholdEvaluationResult - ) => Promise; + ) => Promise; create: ( - teamId: mongoose.Types.ObjectId, - monitorId: mongoose.Types.ObjectId, - startCheckId: mongoose.Types.ObjectId - ) => Promise; - get: (teamId: string, incidentId: string) => Promise; + teamId: string, + monitorId: string, + startCheckId: string + ) => Promise; + get: ( + teamId: string, + incidentId: string + ) => Promise; getAll: ( teamId: string, monitorId: string, @@ -44,7 +44,7 @@ export interface IIncidentService { range: string, resolved?: boolean, resolutionType?: ResolutionType - ) => Promise<{ incidents: IIncident[]; count: number }>; + ) => Promise<{ incidents: IncidentEntity[]; count: number }>; resolve: ( teamId: string, incidentId: string, @@ -52,11 +52,8 @@ export interface IIncidentService { lastCheck?: CheckEntity, resolvedBy?: string, resolutionNote?: string - ) => Promise; - delete: ( - teamId: mongoose.Types.ObjectId, - incidentId: mongoose.Types.ObjectId - ) => Promise; + ) => Promise; + delete: (teamId: string, incidentId: string) => Promise; export: (teamId: string) => Promise>>; cleanupOrphanedIncidents: () => Promise; } @@ -65,8 +62,10 @@ const SERVICE_NAME = "IncidentService"; const logger = getChildLogger(SERVICE_NAME); class IncidentService implements IIncidentService { public SERVICE_NAME: string; - constructor() { + private incidentsRepository: IIncidentsRepository; + constructor(incidentsRepository: IIncidentsRepository) { this.SERVICE_NAME = SERVICE_NAME; + this.incidentsRepository = incidentsRepository; } handleStatusChange = async ( @@ -75,25 +74,27 @@ class IncidentService implements IIncidentService { ) => { if (updatedMonitor.status === "down") { const incident = await this.create( - new mongoose.Types.ObjectId(updatedMonitor.teamId), - new mongoose.Types.ObjectId(updatedMonitor.id), - new mongoose.Types.ObjectId(lastCheck.id) + updatedMonitor.teamId, + updatedMonitor.id, + lastCheck.id ); + return incident; } else if (updatedMonitor.status === "up") { - const incident = await Incident.findOne({ - monitorId: updatedMonitor.id, - teamId: updatedMonitor.teamId, - resolved: false, - }); + const incident = + await this.incidentsRepository.findByMonitorIdAndResolved( + updatedMonitor.id, + updatedMonitor.teamId, + false + ); if (!incident) { return null; } const resolvedIncident = await this.resolve( - updatedMonitor.teamId.toString(), - incident._id.toString(), + updatedMonitor.teamId, + incident.id, "auto", lastCheck ); @@ -107,42 +108,38 @@ class IncidentService implements IIncidentService { lastCheck: CheckEntity, evalResult: ThresholdEvaluationResult ) => { - const existing = await Incident.findOne({ - monitorId: updatedMonitor.id, - teamId: updatedMonitor.teamId, - resolved: false, - }); + const existing = await this.incidentsRepository.findByMonitorIdAndResolved( + updatedMonitor.id, + updatedMonitor.teamId, + false + ); if (evalResult.hasBreach) { if (!existing) { - const incident = await this.create( - new mongoose.Types.ObjectId(updatedMonitor.teamId), - new mongoose.Types.ObjectId(updatedMonitor.id), - new mongoose.Types.ObjectId(lastCheck.id) - ); + const incident = await this.incidentsRepository.create({ + teamId: updatedMonitor.teamId, + monitorId: updatedMonitor.id, + startCheck: lastCheck.id, + }); if (evalResult.notes.length) { - await Incident.updateOne( - { _id: incident._id }, + await this.incidentsRepository.updateById( + incident.id, + updatedMonitor.teamId, { - $set: { - resolutionNote: `threshold breach: ${evalResult.notes.join( - ", " - )}`, - }, + resolutionNote: `threshold breach: ${evalResult.notes.join( + ", " + )}`, } ); } return incident; } if (evalResult.notes.length) { - await Incident.updateOne( - { _id: existing._id }, + await this.incidentsRepository.updateById( + existing.id, + updatedMonitor.teamId, { - $set: { - resolutionNote: `threshold breach: ${evalResult.notes.join( - ", " - )}`, - }, + resolutionNote: `threshold breach: ${evalResult.notes.join(", ")}`, } ); } @@ -150,7 +147,7 @@ class IncidentService implements IIncidentService { } else if (existing) { const resolved = await this.resolve( updatedMonitor.teamId, - existing._id.toString(), + existing.id, "auto", lastCheck ); @@ -160,38 +157,32 @@ class IncidentService implements IIncidentService { return null; }; - create = async ( - teamId: mongoose.Types.ObjectId, - monitorId: mongoose.Types.ObjectId, - startCheckId: mongoose.Types.ObjectId - ) => { - const existing = await Incident.findOne({ + create = async (teamId: string, monitorId: string, startCheckId: string) => { + const existing = await this.incidentsRepository.findByMonitorIdAndResolved( monitorId, teamId, - resolved: false, - }); + false + ); if (existing) { return existing; } - let data: Partial = { - teamId: new mongoose.Types.ObjectId(teamId), - monitorId: new mongoose.Types.ObjectId(monitorId), - startedAt: new Date(), - startCheck: new mongoose.Types.ObjectId(startCheckId), + let data: Partial = { + teamId, + monitorId, + startCheck: startCheckId, }; - const incident = await Incident.create(data); + const incident = await this.incidentsRepository.create(data); return incident; }; get = async (teamId: string, incidentId: string) => { - const incident = await Incident.findOne({ - _id: new mongoose.Types.ObjectId(incidentId), - teamId: new mongoose.Types.ObjectId(teamId), - }) - .populate("monitorId") - .populate("resolvedBy"); + const incident = + await this.incidentsRepository.findByIdWithMonitorAndResolvedBy( + incidentId, + teamId + ); return incident; }; @@ -205,22 +196,24 @@ class IncidentService implements IIncidentService { resolutionType?: ResolutionType ) => { const startDate = getStartDate(range); - const match = { - teamId: teamId, - ...(monitorId && { monitorId }), - createdAt: { $gte: startDate }, - ...(resolved !== undefined && { resolved }), - ...(resolutionType !== undefined && { resolutionType }), - }; const [count, incidents] = await Promise.all([ - Incident.countDocuments(match), - Incident.find(match) - .populate("monitorId") - .populate("resolvedBy") - .sort({ createdAt: -1 }) - .skip(page * rowsPerPage) - .limit(rowsPerPage), + this.incidentsRepository.count( + teamId, + startDate, + monitorId, + resolved, + resolutionType + ), + this.incidentsRepository.findAllWithMonitorAndResolvedBy( + teamId, + page, + rowsPerPage, + startDate, + monitorId, + resolved, + resolutionType + ), ]); return { count, incidents }; }; @@ -233,53 +226,38 @@ class IncidentService implements IIncidentService { resolvedBy?: string, resolutionNote?: string ) => { - const incident = await Incident.findOneAndUpdate( - { _id: incidentId, teamId, resolved: false }, + const resolvedIncident = await this.incidentsRepository.updateById( + incidentId, + teamId, { - $set: { - resolved: true, - endedAt: new Date(), - endCheck: lastCheck - ? new mongoose.Types.ObjectId(lastCheck.id) - : undefined, - resolvedBy: resolvedBy ? resolvedBy : undefined, - resolutionType, - resolutionNote: resolutionNote ? resolutionNote : undefined, - }, - }, - { new: true } + resolved: true, + endedAt: new Date(), + endCheck: lastCheck ? lastCheck.id : undefined, + resolvedBy: resolvedBy ? resolvedBy : undefined, + resolutionType, + resolutionNote: resolutionNote ? resolutionNote : undefined, + } ); - return incident; + return resolvedIncident; }; - delete = async ( - teamId: mongoose.Types.ObjectId, - incidentId: mongoose.Types.ObjectId - ) => { - const result = await Incident.deleteOne({ - _id: new mongoose.Types.ObjectId(incidentId), - teamId: new mongoose.Types.ObjectId(teamId), - }); - return result.deletedCount === 1; + delete = async (teamId: string, incidentId: string) => { + return await this.incidentsRepository.deleteById(incidentId, teamId); }; export = async (teamId: string) => { - const incidents = await Incident.find({ - teamId, - }) - .populate("monitorId") - .populate("resolvedBy") - .lean(); - + const incidents = await this.incidentsRepository.findAllByTeamId(teamId); return incidents.map((incident) => ({ - monitor: incident.monitorId?.name ?? "", - monitorId: incident.monitorId?._id?.toString?.() ?? "", + monitor: incident.monitor.name ?? "", + monitorId: incident.monitor.id ?? "", resolved: incident.resolved, resolutionType: incident.resolutionType ?? "Unresolved", startedAt: incident.startedAt, endedAt: incident.endedAt ?? "Ongoing", - resolvedBy: incident.resolvedBy ? incident.resolvedBy.email ?? "" : "", + resolvedBy: incident.resolvedByUser + ? incident.resolvedByUser.email ?? "" + : "", })); }; diff --git a/server/src/services/infrastructure/NotificationService.ts b/server/src/services/infrastructure/NotificationService.ts index a9c2ac769..16bf2bf49 100644 --- a/server/src/services/infrastructure/NotificationService.ts +++ b/server/src/services/infrastructure/NotificationService.ts @@ -15,7 +15,10 @@ import SettingsService from "@/services/system/SettingsService.js"; import ApiError from "@/utils/ApiError.js"; import { getChildLogger } from "@/logger/Logger.js"; import type { IEmailTransport } from "./NotificationServices/Email.js"; -import type { Monitor as MonitorEntity } from "@/types/domain/index.js"; +import type { + Monitor as MonitorEntity, + Incident, +} from "@/types/domain/index.js"; const SERVICE_NAME = "NotificationService"; const logger = getChildLogger(SERVICE_NAME); @@ -29,7 +32,7 @@ export interface ITestResult { export interface INotificationService { handleNotifications: ( monitor: MonitorEntity, - incident: IIncident + incident: Incident ) => Promise; testNotificationChannels: ( monitorId: string, @@ -58,7 +61,7 @@ class NotificationService implements INotificationService { this.webhookService = new WebhookService(); } - handleNotifications = async (monitor: MonitorEntity, incident: IIncident) => { + handleNotifications = async (monitor: MonitorEntity, incident: Incident) => { const notificationIds = monitor.notificationChannels || []; if (notificationIds.length === 0) { @@ -89,7 +92,7 @@ class NotificationService implements INotificationService { private sendForChannel = async ( channel: INotificationChannel, monitor: MonitorEntity, - incident: IIncident + incident: Incident ): Promise => { try { switch (channel.type) { diff --git a/server/src/services/infrastructure/NotificationServices/Discord.ts b/server/src/services/infrastructure/NotificationServices/Discord.ts index c0d0aeeb1..1ea32db3c 100644 --- a/server/src/services/infrastructure/NotificationServices/Discord.ts +++ b/server/src/services/infrastructure/NotificationServices/Discord.ts @@ -1,5 +1,5 @@ -import { INotificationChannel, IIncident } from "@/db/models/index.js"; -import type { Monitor } from "@/types/domain/index.js"; +import { INotificationChannel } from "@/db/models/index.js"; +import type { Monitor, Incident } from "@/types/domain/index.js"; import { IAlert, IMessageService } from "./IMessageService.js"; import got from "got"; import ApiError from "@/utils/ApiError.js"; @@ -49,7 +49,7 @@ class DiscordService implements IMessageService { }; }; - buildAlert = (monitor: Monitor, incident: IIncident) => { + buildAlert = (monitor: Monitor, incident: Incident) => { const name = monitor?.name || "Unnamed monitor"; const monitorStatus = monitor?.status || "unknown status"; const url = monitor?.url || "no URL"; diff --git a/server/src/services/infrastructure/NotificationServices/Email.ts b/server/src/services/infrastructure/NotificationServices/Email.ts index 3a321c1a0..1676d8a44 100644 --- a/server/src/services/infrastructure/NotificationServices/Email.ts +++ b/server/src/services/infrastructure/NotificationServices/Email.ts @@ -1,5 +1,5 @@ -import { INotificationChannel, IIncident } from "@/db/models/index.js"; -import type { Monitor } from "@/types/domain/index.js"; +import { INotificationChannel } from "@/db/models/index.js"; +import type { Monitor, Incident } from "@/types/domain/index.js"; import { IMessageService, IAlert } from "./IMessageService.js"; import nodemailer, { Transporter } from "nodemailer"; @@ -121,7 +121,7 @@ class EmailService implements IEmailService { } }; - buildAlert = (monitor: Monitor, incident: IIncident) => { + buildAlert = (monitor: Monitor, incident: Incident) => { const name = monitor?.name || "Unnamed monitor"; const monitorStatus = monitor?.status || "unknown status"; const url = monitor?.url || "no URL"; diff --git a/server/src/services/infrastructure/NotificationServices/IMessageService.ts b/server/src/services/infrastructure/NotificationServices/IMessageService.ts index 9840ec297..0a354ee81 100644 --- a/server/src/services/infrastructure/NotificationServices/IMessageService.ts +++ b/server/src/services/infrastructure/NotificationServices/IMessageService.ts @@ -1,9 +1,9 @@ -import { - INotificationChannel, - IIncident, +import { INotificationChannel } from "@/db/models/index.js"; +import type { + Monitor, + Incident, ResolutionType, -} from "@/db/models/index.js"; -import type { Monitor } from "@/types/domain/index.js"; +} from "@/types/domain/index.js"; export interface IAlert { name: string; @@ -18,7 +18,7 @@ export interface IAlert { alertTime: Date; } export interface IMessageService { - buildAlert: (monitor: Monitor, incident: IIncident) => IAlert; + buildAlert: (monitor: Monitor, incident: Incident) => IAlert; sendMessage: ( alert: IAlert, channel: INotificationChannel diff --git a/server/src/services/infrastructure/NotificationServices/Slack.ts b/server/src/services/infrastructure/NotificationServices/Slack.ts index 7327fef14..f177caff5 100644 --- a/server/src/services/infrastructure/NotificationServices/Slack.ts +++ b/server/src/services/infrastructure/NotificationServices/Slack.ts @@ -1,7 +1,7 @@ -import { INotificationChannel, IIncident } from "@/db/models/index.js"; +import { INotificationChannel } from "@/db/models/index.js"; import { IAlert, IMessageService } from "./IMessageService.js"; import got from "got"; -import { Monitor } from "@/types/domain/index.js"; +import { Monitor, Incident } from "@/types/domain/index.js"; import { getChildLogger } from "@/logger/Logger.js"; const SERVICE_NAME = "SlackService"; @@ -110,7 +110,7 @@ class SlackService implements IMessageService { ]; }; - buildAlert = (monitor: Monitor, incident: IIncident) => { + buildAlert = (monitor: Monitor, incident: Incident) => { const name = monitor?.name || "Unnamed monitor"; const monitorStatus = monitor?.status || "unknown status"; const url = monitor?.url || "no URL"; diff --git a/server/src/services/infrastructure/NotificationServices/Webhook.ts b/server/src/services/infrastructure/NotificationServices/Webhook.ts index 0f73716e8..dffda0642 100644 --- a/server/src/services/infrastructure/NotificationServices/Webhook.ts +++ b/server/src/services/infrastructure/NotificationServices/Webhook.ts @@ -1,9 +1,9 @@ -import { INotificationChannel, IIncident } from "@/db/models/index.js"; +import { INotificationChannel } from "@/db/models/index.js"; import { IAlert, IMessageService } from "./IMessageService.js"; import ApiError from "@/utils/ApiError.js"; import got from "got"; import { getChildLogger } from "@/logger/Logger.js"; -import type { Monitor } from "@/types/domain/index.js"; +import type { Monitor, Incident } from "@/types/domain/index.js"; const SERVICE_NAME = "WebhookService"; const logger = getChildLogger(SERVICE_NAME); @@ -14,7 +14,7 @@ class WebhookService implements IMessageService { this.SERVICE_NAME = SERVICE_NAME; } - buildAlert = (monitor: Monitor, incident: IIncident) => { + buildAlert = (monitor: Monitor, incident: Incident) => { const name = monitor?.name || "Unnamed monitor"; const monitorStatus = monitor?.status || "unknown status"; const url = monitor?.url || "no URL"; diff --git a/server/src/types/domain/incident.ts b/server/src/types/domain/incident.ts new file mode 100644 index 000000000..1b1e9594d --- /dev/null +++ b/server/src/types/domain/incident.ts @@ -0,0 +1,28 @@ +export const ResolutionTypes = ["auto", "manual"] as const; +export type ResolutionType = (typeof ResolutionTypes)[number]; +import type { MonitorType, MonitorStatus } from "@/types/domain/index.js"; +export interface Incident { + id: string; + monitorId: string; + teamId: string; + startedAt: Date; + startCheck: string; + endedAt?: Date; + endCheck?: string; + resolved: boolean; + resolvedBy?: string; + resolutionType?: ResolutionType; + resolutionNote?: string; +} + +export interface IncidentWithDetails extends Incident { + monitor: { + id: string; + name: string; + type: MonitorType; + status: MonitorStatus; + }; + resolvedByUser?: { + email: string; + }; +} diff --git a/server/src/types/domain/index.ts b/server/src/types/domain/index.ts index 6757eeca5..42303754b 100644 --- a/server/src/types/domain/index.ts +++ b/server/src/types/domain/index.ts @@ -1,3 +1,4 @@ export * from "@/types/domain/monitor.js"; export * from "@/types/domain/check.js"; export * from "@/types/domain/monitorStats.js"; +export * from "@/types/domain/incident.js"; diff --git a/server/src/validation/incidents.ts b/server/src/validation/incidents.ts index 5fa5bd77f..fe84081ae 100644 --- a/server/src/validation/incidents.ts +++ b/server/src/validation/incidents.ts @@ -1,6 +1,6 @@ import { z } from "zod"; import mongoose from "mongoose"; -import { ResolutionTypes } from "@/db/models/index.js"; +import { ResolutionTypes } from "@/types/domain/index.js"; export const getIncidentQuerySchema = z.object({ id: z.string().refine((val) => mongoose.Types.ObjectId.isValid(val), { @@ -17,7 +17,10 @@ export const getIncidentsQuerySchema = z.object({ if (val === undefined) return undefined; if (val === "true") return true; if (val === "false") return false; - ctx.addIssue({ code: "custom", message: "resolved must be 'true' or 'false'" }); + ctx.addIssue({ + code: "custom", + message: "resolved must be 'true' or 'false'", + }); return z.NEVER; }), page: z @@ -43,15 +46,24 @@ export const getIncidentsQuerySchema = z.object({ if (!val) return; const num = Number(val); if (Number.isNaN(num)) { - ctx.addIssue({ code: "custom", message: "rowsPerPage must be a number" }); + ctx.addIssue({ + code: "custom", + message: "rowsPerPage must be a number", + }); return z.NEVER; } if (num < 0) { - ctx.addIssue({ code: "custom", message: "rowsPerPage must be greater than 0" }); + ctx.addIssue({ + code: "custom", + message: "rowsPerPage must be greater than 0", + }); return z.NEVER; } if (num > 100) { - ctx.addIssue({ code: "custom", message: "rowsPerPage must be less than or equal to 100" }); + ctx.addIssue({ + code: "custom", + message: "rowsPerPage must be less than or equal to 100", + }); return z.NEVER; } return num; @@ -68,4 +80,3 @@ export const getIncidentsQuerySchema = z.object({ export const patchIncidentsBodySchema = z.object({ resolutionNote: z.string().max(200).optional(), }); -