incidents repo and data reversal

This commit is contained in:
Alex Holliday committed 2026-01-06 20:49:06 +00:00
1 parent 605b4713af
commit 51081a6a0e
32 files changed
+537 -241

No files matched your search

@@ -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) => {
})}
</Typography>
{(() => {
const href = `/${getMonitorPath(check.metadata.type)}/${check.metadata.monitorId}`;
const href = `/${getMonitorPath(check.type)}/${check.monitorId}`;
return href ? (
<Typography variant="body2" sx={{ mt: 0.5 }}>
<Link
+2 -2
View File
@@ -1,4 +1,4 @@
import type { ICheck, CheckTimingPhases } from "@/types/check";
import type { Check, CheckTimingPhases } from "@/types/check";
import { PieChart, Pie, ResponsiveContainer, Tooltip, Legend } from "recharts";
import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography";
@@ -6,7 +6,7 @@ import { alpha, useTheme } from "@mui/material/styles";
import { useState } from "react";
import { BaseBox } from "@/components/design-elements";
import { useTranslation } from "react-i18next";
type TimingsChartProps = { check: ICheck | null };
type TimingsChartProps = { check: Check | null };
export type TimingSegment = {
name: string;
@@ -24,18 +24,17 @@ export const HeatmapResponseTime = ({
}
if (!checks || checks.length === 0) return null;
let data = Array<any>();
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<ICheck | { status: "placeholder" }>;
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 (
<Box sx={{ width: "100%" }}>
@@ -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 = ({
>
<Typography>
{formatDateWithTz(
check?.checkedAt,
check?.createdAt,
"ddd, MMMM D, YYYY, HH:mm A",
uiTimezone
)}
@@ -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<any>();
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);
@@ -66,7 +66,7 @@ export const BarDockerCount = ({
) : (
<ResponsiveContainer width="100%" height={200}>
<BarChart
data={data}
data={[...data].reverse()}
margin={{ top: 8, right: 8, left: isSmall ? 4 : 12, bottom: 8 }}
>
<defs>
@@ -62,7 +62,7 @@ export const HistogramDockerPercentage = ({
) : (
<ResponsiveContainer width="100%" height={200}>
<AreaChart
data={data}
data={[...data].reverse()}
margin={{ top: 8, right: 8, left: isSmall ? 0 : 8, bottom: 8 }}
>
<CartesianGrid
@@ -117,11 +117,12 @@ export const HistogramInfrastructure = ({
}) => {
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 (
<BaseChart icon={null} title={title}>
<ResponsiveContainer width="100%" height={200}>
<AreaChart data={type === "temp" ? avgTemps : checks}>
<AreaChart data={type === "temp" ? avgTemps : data}>
<XAxis
dataKey={xKey}
tick={(props) => <XTick {...props} range={range} />}
+2 -2
View File
@@ -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<ApiResponse<ICheck>>(
const { response, loading, error } = useGet<ApiResponse<Check>>(
`/checks/${id}`
);
+3 -2
View File
@@ -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 = () => {
</Stack>
<ChecksTable
checks={checks}
monitors={monitors}
hasMore={hasMore}
page={page}
setPage={setPage}
+12 -9
View File
@@ -6,27 +6,26 @@ import {
} from "@/components/design-elements";
import Box from "@mui/material/Box";
import type { Header } from "@/components/design-elements/Table";
import type { IMonitor } from "@/types/monitor";
import { useTranslation } from "react-i18next";
import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks";
import type { ICheck } from "@/types/check";
import type { MonitorStatus } from "@/types/monitor";
import { useNavigate } from "react-router";
type CheckWithMonitor = ICheck & {
metadata?: { monitorId?: { name?: string } };
};
import type { Check } from "@/types/check";
export const ChecksTable = ({
checks,
monitors,
hasMore,
page,
setPage,
rowsPerPage,
setRowsPerPage,
}: {
checks: CheckWithMonitor[];
checks: Check[];
monitors: IMonitor[] | null;
hasMore?: boolean;
page: number;
setPage: (page: number) => void;
@@ -38,12 +37,15 @@ export const ChecksTable = ({
const navigate = useNavigate();
const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<CheckWithMonitor>[] = [
const headers: Header<Check>[] = [
{
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 <ValueLabel value={value} text={String(code)} />;
@@ -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")}
/>
@@ -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<ApiResponse<IIncident>>(`/incidents/${id}`);
const { response } = useGet<ApiResponse<IncidentWithDetails>>(
`/incidents/${id}`
);
const incident = response?.data || null;
if (!incident) {
@@ -45,11 +47,11 @@ const IncidentDetailsPage = () => {
<Stack direction={{ xs: "column", md: "row" }} gap={theme.spacing(8)}>
<StatBox
title={t("monitors.common.stats.monitor")}
subtitle={incident.monitorId?.name || "N/A"}
subtitle={incident.monitor?.name || "N/A"}
onClick={() => {
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 = () => {
<ResolutionCard
resolved={incident.resolved}
type={incident.resolutionType}
by={incident.resolvedBy?.email}
by={incident.resolvedByUser?.email}
note={incident.resolutionNote}
timestampLabel={
incident.resolved && incident.endedAt
+8 -8
View File
@@ -13,7 +13,7 @@ import { usePatch } from "@/hooks/UseApi";
import { useTranslation } from "react-i18next";
import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks";
import type { IIncident } from "@/types/incident";
import type { IncidentWithDetails } from "@/types/incident";
import { useNavigate } from "react-router";
export const IncidentTable = ({
@@ -25,7 +25,7 @@ export const IncidentTable = ({
setRowsPerPage,
refetch,
}: {
incidents: IIncident[];
incidents: IncidentWithDetails[];
count: number;
page: number;
setPage: (page: number) => void;
@@ -39,12 +39,12 @@ export const IncidentTable = ({
const navigate = useNavigate();
const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<IIncident>[] = [
const headers: Header<IncidentWithDetails>[] = [
{
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 ? (
<StatusLabel status={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")}
+2 -2
View File
@@ -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<ApiResponse<{ count: number; incidents: IIncident[] }>>(
} = useGet<ApiResponse<{ count: number; incidents: IncidentWithDetails[] }>>(
`/incidents?page=${page}&rowsPerPage=${rowsPerPage}&range=${range}${
selectedMonitorId && selectedMonitorId !== "all"
? `&monitorId=${selectedMonitorId}`
+28 -20
View File
@@ -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;
+21 -9
View File
@@ -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;
};
}
+3 -4
View File
@@ -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;
+2 -2
View File
@@ -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";
+3 -1
View File
@@ -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,
@@ -0,0 +1,49 @@
import type {
Incident as IncidentEntity,
IncidentWithDetails,
ResolutionType,
} from "@/types/domain/index.js";
export interface IIncidentsRepository {
// create
create(incident: Partial<IncidentEntity>): Promise<IncidentEntity>;
// single fetch
findByMonitorIdAndResolved(
monitorId: string,
teamId: string,
resolved: boolean
): Promise<IncidentEntity | null>;
findByIdWithMonitorAndResolvedBy(
incidentId: string,
teamId: string
): Promise<IncidentWithDetails | null>;
// collection fetch
count(
teamId: string,
startDate: Date,
monitorId?: string,
resolved?: boolean,
resolutionType?: ResolutionType
): Promise<number>;
findAllWithMonitorAndResolvedBy(
teamId: string,
page: number,
rowsPerPage: number,
startDate: Date,
monitorId?: string,
resolved?: boolean,
resolutionType?: ResolutionType
): Promise<IncidentWithDetails[]>;
findAllByTeamId(teamId: string): Promise<IncidentWithDetails[]>;
// update
updateById(
incidentId: string,
teamId: string,
updates: Partial<IncidentEntity>
): Promise<IncidentEntity | null>;
// delete
deleteById(incidentId: string, teamId: string): Promise<boolean>;
}
export default IIncidentsRepository;
@@ -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<IIncident, "monitorId" | "resolvedBy"> & {
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<IncidentEntity>) => {
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<IncidentPopulated>();
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<IncidentPopulated[]>();
return incidents.map((incident) => this.toEntityWithDetails(incident));
};
findAllByTeamId = async (teamId: string) => {
const incidents = await Incident.find({
teamId,
})
.populate("monitorId")
.populate("resolvedBy")
.lean<IncidentPopulated[]>();
return incidents.map((incident) => this.toEntityWithDetails(incident));
};
updateById = async (
incidentId: string,
teamId: string,
updates: Partial<IncidentEntity>
) => {
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;
+3
View File
@@ -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";
+102 -124
View File
@@ -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<IIncident, "monitorId" | "resolvedBy"> & {
monitorId: IMonitor;
resolvedBy?: IUser | null;
};
import type { IIncidentsRepository } from "@/repositories/index.js";
export interface IIncidentService {
handleStatusChange: (
updatedMonitor: MonitorEntity,
lastCheck: CheckEntity
) => Promise<IIncident | null>;
) => Promise<IncidentEntity | null>;
handleThresholdBreach: (
updatedMonitor: MonitorEntity,
lastCheck: CheckEntity,
evalResult: ThresholdEvaluationResult
) => Promise<IIncident | null>;
) => Promise<IncidentEntity | null>;
create: (
teamId: mongoose.Types.ObjectId,
monitorId: mongoose.Types.ObjectId,
startCheckId: mongoose.Types.ObjectId
) => Promise<IIncident>;
get: (teamId: string, incidentId: string) => Promise<IIncident | null>;
teamId: string,
monitorId: string,
startCheckId: string
) => Promise<IncidentEntity>;
get: (
teamId: string,
incidentId: string
) => Promise<IncidentWithDetails | null>;
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<IIncident | null>;
delete: (
teamId: mongoose.Types.ObjectId,
incidentId: mongoose.Types.ObjectId
) => Promise<boolean>;
) => Promise<IncidentEntity | null>;
delete: (teamId: string, incidentId: string) => Promise<boolean>;
export: (teamId: string) => Promise<Array<Record<string, unknown>>>;
cleanupOrphanedIncidents: () => Promise<boolean>;
}
@@ -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<IIncident> = {
teamId: new mongoose.Types.ObjectId(teamId),
monitorId: new mongoose.Types.ObjectId(monitorId),
startedAt: new Date(),
startCheck: new mongoose.Types.ObjectId(startCheckId),
let data: Partial<IncidentEntity> = {
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<IncidentPopulated[]>();
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 ?? ""
: "",
}));
};
@@ -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<void>;
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<boolean> => {
try {
switch (channel.type) {
@@ -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";
@@ -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";
@@ -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
@@ -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";
@@ -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";
+28
View File
@@ -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;
};
}
+1
View File
@@ -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";
+17 -6
View File
@@ -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(),
});