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 { BaseBox } from "@/components/design-elements";
import { useAppSelector } from "@/hooks/AppHooks"; import { useAppSelector } from "@/hooks/AppHooks";
import type { ICheck } from "@/types/check"; import type { Check } from "@/types/check";
import type { MonitorStatus } from "@/types/monitor"; import type { MonitorStatus } from "@/types/monitor";
import { formatDateWithTz } from "@/utils/TimeUtils"; import { formatDateWithTz } from "@/utils/TimeUtils";
import { useTheme } from "@mui/material/styles"; import { useTheme } from "@mui/material/styles";
@@ -16,7 +16,7 @@ import { getMonitorPath } from "@/utils/MonitorUtils";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
type CheckDetailsCardProps = { type CheckDetailsCardProps = {
check: ICheck; check: Check;
}; };
export const CheckDetailsCard = ({ check }: CheckDetailsCardProps) => { export const CheckDetailsCard = ({ check }: CheckDetailsCardProps) => {
@@ -50,7 +50,7 @@ export const CheckDetailsCard = ({ check }: CheckDetailsCardProps) => {
const httpText = Number.isFinite(httpStatusCode) const httpText = Number.isFinite(httpStatusCode)
? String(httpStatusCode) ? String(httpStatusCode)
: "-"; : "-";
const typeText = check?.metadata?.type ?? "-"; const typeText = check?.type ?? "-";
const checkedAtText = check?.createdAt const checkedAtText = check?.createdAt
? formatDateWithTz(check.createdAt, "ddd, MMM D, YYYY, HH:mm A", uiTimezone) ? formatDateWithTz(check.createdAt, "ddd, MMM D, YYYY, HH:mm A", uiTimezone)
: "-"; : "-";
@@ -71,7 +71,7 @@ export const CheckDetailsCard = ({ check }: CheckDetailsCardProps) => {
})} })}
</Typography> </Typography>
{(() => { {(() => {
const href = `/${getMonitorPath(check.metadata.type)}/${check.metadata.monitorId}`; const href = `/${getMonitorPath(check.type)}/${check.monitorId}`;
return href ? ( return href ? (
<Typography variant="body2" sx={{ mt: 0.5 }}> <Typography variant="body2" sx={{ mt: 0.5 }}>
<Link <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 { PieChart, Pie, ResponsiveContainer, Tooltip, Legend } from "recharts";
import Stack from "@mui/material/Stack"; import Stack from "@mui/material/Stack";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
@@ -6,7 +6,7 @@ import { alpha, useTheme } from "@mui/material/styles";
import { useState } from "react"; import { useState } from "react";
import { BaseBox } from "@/components/design-elements"; import { BaseBox } from "@/components/design-elements";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
type TimingsChartProps = { check: ICheck | null }; type TimingsChartProps = { check: Check | null };
export type TimingSegment = { export type TimingSegment = {
name: string; name: string;
@@ -24,18 +24,17 @@ export const HeatmapResponseTime = ({
} }
if (!checks || checks.length === 0) return null; if (!checks || checks.length === 0) return null;
let data = Array<any>();
if (!checks || checks.length === 0) { const latestChecks = checks.slice(-25).reverse();
checks = [];
} let data: Array<ICheck | { status: "placeholder" }>;
if (checks.length !== 25) { if (latestChecks.length !== 25) {
const placeholders = Array(25 - checks.length).fill({ const placeholders = Array(25 - latestChecks.length).fill({
status: "placeholder", status: "placeholder" as const,
}); });
data = [...checks, ...placeholders]; data = [...latestChecks, ...placeholders];
} else { } else {
data = checks; data = latestChecks;
} }
return ( return (
<Box sx={{ width: "100%" }}> <Box sx={{ width: "100%" }}>
@@ -3,15 +3,17 @@ import Tooltip from "@mui/material/Tooltip";
import Typography from "@mui/material/Typography"; import Typography from "@mui/material/Typography";
import { formatDateWithTz } from "@/utils/TimeUtils"; import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks"; import { useAppSelector } from "@/hooks/AppHooks";
import type { LatestCheck } from "@/types/check"; import type { Check } from "@/types/check";
import { useTheme } from "@mui/material/styles"; import { useTheme } from "@mui/material/styles";
type HeatmapCheck = Check | { status: "placeholder" };
export const HeatmapResponseTimeTooltip = ({ export const HeatmapResponseTimeTooltip = ({
children, children,
check, check,
}: { }: {
children: React.ReactElement; children: React.ReactElement;
check: LatestCheck; check: HeatmapCheck;
}) => { }) => {
const uiTimezone = useAppSelector((state: any) => state.ui.timezone); const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const theme = useTheme(); const theme = useTheme();
@@ -47,7 +49,7 @@ export const HeatmapResponseTimeTooltip = ({
> >
<Typography> <Typography>
{formatDateWithTz( {formatDateWithTz(
check?.checkedAt, check?.createdAt,
"ddd, MMMM D, YYYY, HH:mm A", "ddd, MMMM D, YYYY, HH:mm A",
uiTimezone uiTimezone
)} )}
@@ -22,7 +22,10 @@ export const HistogramResponseTime = ({
if (!Array.isArray(checks) || checks.length === 0) return null; 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>(); let data = Array<any>();
if (!normalized || normalized.length === 0) { if (!normalized || normalized.length === 0) {
@@ -36,7 +39,6 @@ export const HistogramResponseTime = ({
} else { } else {
data = normalized; data = normalized;
} }
const chartHeight = typeof height === "number" ? `${height}px` : height; const chartHeight = typeof height === "number" ? `${height}px` : height;
const gridGap = gap ?? theme.spacing(0.5); const gridGap = gap ?? theme.spacing(0.5);
@@ -66,7 +66,7 @@ export const BarDockerCount = ({
) : ( ) : (
<ResponsiveContainer width="100%" height={200}> <ResponsiveContainer width="100%" height={200}>
<BarChart <BarChart
data={data} data={[...data].reverse()}
margin={{ top: 8, right: 8, left: isSmall ? 4 : 12, bottom: 8 }} margin={{ top: 8, right: 8, left: isSmall ? 4 : 12, bottom: 8 }}
> >
<defs> <defs>
@@ -62,7 +62,7 @@ export const HistogramDockerPercentage = ({
) : ( ) : (
<ResponsiveContainer width="100%" height={200}> <ResponsiveContainer width="100%" height={200}>
<AreaChart <AreaChart
data={data} data={[...data].reverse()}
margin={{ top: 8, right: 8, left: isSmall ? 0 : 8, bottom: 8 }} margin={{ top: 8, right: 8, left: isSmall ? 0 : 8, bottom: 8 }}
> >
<CartesianGrid <CartesianGrid
@@ -117,11 +117,12 @@ export const HistogramInfrastructure = ({
}) => { }) => {
const theme = useTheme(); const theme = useTheme();
const uniqueId = useId(); const uniqueId = useId();
let data = checks.reverse();
let avgTemps: { bucketDate: string; avg_temp: number | null }[] = []; let avgTemps: { bucketDate: string; avg_temp: number | null }[] = [];
let tempYDomain: number[] = []; let tempYDomain: number[] = [];
if (type === "temp") { if (type === "temp") {
avgTemps = checks.map((check) => { avgTemps = data.map((check) => {
const temps = check.cpu?.temperature || []; const temps = check.cpu?.temperature || [];
if (temps.length === 0) return { ...check, avg_temp: null }; if (temps.length === 0) return { ...check, avg_temp: null };
const totalTemp = temps.reduce((sum, temp) => sum + (temp || 0), 0); const totalTemp = temps.reduce((sum, temp) => sum + (temp || 0), 0);
@@ -139,7 +140,7 @@ export const HistogramInfrastructure = ({
return ( return (
<BaseChart icon={null} title={title}> <BaseChart icon={null} title={title}>
<ResponsiveContainer width="100%" height={200}> <ResponsiveContainer width="100%" height={200}>
<AreaChart data={type === "temp" ? avgTemps : checks}> <AreaChart data={type === "temp" ? avgTemps : data}>
<XAxis <XAxis
dataKey={xKey} dataKey={xKey}
tick={(props) => <XTick {...props} range={range} />} 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 { useParams } from "react-router";
import { useGet } from "@/hooks/UseApi"; import { useGet } from "@/hooks/UseApi";
import type { ICheck } from "@/types/check"; import type { Check } from "@/types/check";
import type { ApiResponse } from "@/types/api"; import type { ApiResponse } from "@/types/api";
const CheckDetails = () => { const CheckDetails = () => {
const { id } = useParams(); const { id } = useParams();
const { response, loading, error } = useGet<ApiResponse<ICheck>>( const { response, loading, error } = useGet<ApiResponse<Check>>(
`/checks/${id}` `/checks/${id}`
); );
+3 -2
View File
@@ -12,7 +12,7 @@ import type { SelectChangeEvent } from "@mui/material/Select";
import { useGet } from "@/hooks/UseApi"; import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/types/api"; import type { ApiResponse } from "@/types/api";
import type { IMonitor } from "@/types/monitor"; import type { IMonitor } from "@/types/monitor";
import type { ICheck } from "@/types/check"; import type { Check } from "@/types/check";
import { config } from "@/config/index"; import { config } from "@/config/index";
const ChecksPage = () => { const ChecksPage = () => {
@@ -29,7 +29,7 @@ const ChecksPage = () => {
const monitors: IMonitor[] = monitorResponse?.data || []; const monitors: IMonitor[] = monitorResponse?.data || [];
const { response: checksResponse, loading: checksLoading } = useGet< 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}${ `/checks?page=${page}&rowsPerPage=${rowsPerPage}&range=${range}&status=${status}${
selectedMonitorId !== "all" ? `&monitorId=${selectedMonitorId}` : "" selectedMonitorId !== "all" ? `&monitorId=${selectedMonitorId}` : ""
@@ -101,6 +101,7 @@ const ChecksPage = () => {
</Stack> </Stack>
<ChecksTable <ChecksTable
checks={checks} checks={checks}
monitors={monitors}
hasMore={hasMore} hasMore={hasMore}
page={page} page={page}
setPage={setPage} setPage={setPage}
+12 -9
View File
@@ -6,27 +6,26 @@ import {
} from "@/components/design-elements"; } from "@/components/design-elements";
import Box from "@mui/material/Box"; import Box from "@mui/material/Box";
import type { Header } from "@/components/design-elements/Table"; import type { Header } from "@/components/design-elements/Table";
import type { IMonitor } from "@/types/monitor";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatDateWithTz } from "@/utils/TimeUtils"; import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks"; import { useAppSelector } from "@/hooks/AppHooks";
import type { ICheck } from "@/types/check";
import type { MonitorStatus } from "@/types/monitor"; import type { MonitorStatus } from "@/types/monitor";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
import type { Check } from "@/types/check";
type CheckWithMonitor = ICheck & {
metadata?: { monitorId?: { name?: string } };
};
export const ChecksTable = ({ export const ChecksTable = ({
checks, checks,
monitors,
hasMore, hasMore,
page, page,
setPage, setPage,
rowsPerPage, rowsPerPage,
setRowsPerPage, setRowsPerPage,
}: { }: {
checks: CheckWithMonitor[]; checks: Check[];
monitors: IMonitor[] | null;
hasMore?: boolean; hasMore?: boolean;
page: number; page: number;
setPage: (page: number) => void; setPage: (page: number) => void;
@@ -38,12 +37,15 @@ export const ChecksTable = ({
const navigate = useNavigate(); const navigate = useNavigate();
const getHeaders = (t: Function, uiTimezone: string) => { const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<CheckWithMonitor>[] = [ const headers: Header<Check>[] = [
{ {
id: "monitorName", id: "monitorName",
content: t("common.table.headers.monitor"), content: t("common.table.headers.monitor"),
render: (row) => { 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"), content: t("checks.table.headers.statusCode"),
render: (row) => { render: (row) => {
const code = row.httpStatusCode; const code = row.httpStatusCode;
if (!code) return "N/A";
const value = const value =
code < 300 ? "positive" : code < 400 ? "neutral" : "negative"; code < 300 ? "positive" : code < 400 ? "neutral" : "negative";
return <ValueLabel value={value} text={String(code)} />; return <ValueLabel value={value} text={String(code)} />;
@@ -108,7 +111,7 @@ export const ChecksTable = ({
headers={headers} headers={headers}
data={checks} data={checks}
onRowClick={(row) => { onRowClick={(row) => {
navigate(`/checks/${row._id}`); navigate(`/checks/${row.id}`);
}} }}
emptyViewText={t("checks.table.empty")} emptyViewText={t("checks.table.empty")}
/> />
@@ -7,7 +7,7 @@ import { useTheme } from "@mui/material/styles";
import { useNavigate, useParams } from "react-router"; import { useNavigate, useParams } from "react-router";
import { useGet } from "@/hooks/UseApi"; import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/types/api"; import type { ApiResponse } from "@/types/api";
import type { IIncident } from "@/types/incident"; import type { IncidentWithDetails } from "@/types/incident";
import { formatDateWithTz } from "@/utils/TimeUtils"; import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks"; import { useAppSelector } from "@/hooks/AppHooks";
import prettyMilliseconds from "pretty-ms"; import prettyMilliseconds from "pretty-ms";
@@ -22,7 +22,9 @@ const IncidentDetailsPage = () => {
const uiTimezone = useAppSelector((state: any) => state.ui.timezone); const uiTimezone = useAppSelector((state: any) => state.ui.timezone);
const navigate = useNavigate(); const navigate = useNavigate();
const { response } = useGet<ApiResponse<IIncident>>(`/incidents/${id}`); const { response } = useGet<ApiResponse<IncidentWithDetails>>(
`/incidents/${id}`
);
const incident = response?.data || null; const incident = response?.data || null;
if (!incident) { if (!incident) {
@@ -45,11 +47,11 @@ const IncidentDetailsPage = () => {
<Stack direction={{ xs: "column", md: "row" }} gap={theme.spacing(8)}> <Stack direction={{ xs: "column", md: "row" }} gap={theme.spacing(8)}>
<StatBox <StatBox
title={t("monitors.common.stats.monitor")} title={t("monitors.common.stats.monitor")}
subtitle={incident.monitorId?.name || "N/A"} subtitle={incident.monitor?.name || "N/A"}
onClick={() => { onClick={() => {
const type = incident.monitorId.type as MonitorType; const type = incident.monitor.type;
const path = getMonitorPath(type); const path = getMonitorPath(type);
const id = (incident.monitorId as any)?._id; const id = incident.monitor?.id;
if (id) navigate(`/${path}/${id}`); if (id) navigate(`/${path}/${id}`);
}} }}
/> />
@@ -78,7 +80,7 @@ const IncidentDetailsPage = () => {
<ResolutionCard <ResolutionCard
resolved={incident.resolved} resolved={incident.resolved}
type={incident.resolutionType} type={incident.resolutionType}
by={incident.resolvedBy?.email} by={incident.resolvedByUser?.email}
note={incident.resolutionNote} note={incident.resolutionNote}
timestampLabel={ timestampLabel={
incident.resolved && incident.endedAt incident.resolved && incident.endedAt
+8 -8
View File
@@ -13,7 +13,7 @@ import { usePatch } from "@/hooks/UseApi";
import { useTranslation } from "react-i18next"; import { useTranslation } from "react-i18next";
import { formatDateWithTz } from "@/utils/TimeUtils"; import { formatDateWithTz } from "@/utils/TimeUtils";
import { useAppSelector } from "@/hooks/AppHooks"; import { useAppSelector } from "@/hooks/AppHooks";
import type { IIncident } from "@/types/incident"; import type { IncidentWithDetails } from "@/types/incident";
import { useNavigate } from "react-router"; import { useNavigate } from "react-router";
export const IncidentTable = ({ export const IncidentTable = ({
@@ -25,7 +25,7 @@ export const IncidentTable = ({
setRowsPerPage, setRowsPerPage,
refetch, refetch,
}: { }: {
incidents: IIncident[]; incidents: IncidentWithDetails[];
count: number; count: number;
page: number; page: number;
setPage: (page: number) => void; setPage: (page: number) => void;
@@ -39,12 +39,12 @@ export const IncidentTable = ({
const navigate = useNavigate(); const navigate = useNavigate();
const getHeaders = (t: Function, uiTimezone: string) => { const getHeaders = (t: Function, uiTimezone: string) => {
const headers: Header<IIncident>[] = [ const headers: Header<IncidentWithDetails>[] = [
{ {
id: "name", id: "name",
content: t("common.table.headers.monitor"), content: t("common.table.headers.monitor"),
render: (row) => { render: (row) => {
return row.monitorId?.name || "N/A"; return row.monitor?.name || "N/A";
}, },
}, },
{ {
@@ -75,7 +75,7 @@ export const IncidentTable = ({
id: "status", id: "status",
content: t("incidents.table.headers.monitorStatus"), content: t("incidents.table.headers.monitorStatus"),
render: (row) => { render: (row) => {
const status = row.monitorId?.status; const status = row.monitor?.status;
return status ? ( return status ? (
<StatusLabel status={status} /> <StatusLabel status={status} />
) : ( ) : (
@@ -106,7 +106,7 @@ export const IncidentTable = ({
id: "resolvedBy", id: "resolvedBy",
content: t("incidents.table.headers.resolvedBy"), content: t("incidents.table.headers.resolvedBy"),
render: (row) => { render: (row) => {
return row.resolvedBy?.email || "N/A"; return row.resolvedByUser?.email || "N/A";
}, },
}, },
{ {
@@ -118,7 +118,7 @@ export const IncidentTable = ({
loading={isPatching} loading={isPatching}
onClick={async (e) => { onClick={async (e) => {
e.stopPropagation(); e.stopPropagation();
await patch(`/incidents/${row._id}/resolve`, { await patch(`/incidents/${row.id}/resolve`, {
resolutionNote: "Resolved via UI", resolutionNote: "Resolved via UI",
}); });
refetch(); refetch();
@@ -158,7 +158,7 @@ export const IncidentTable = ({
headers={headers} headers={headers}
data={incidents} data={incidents}
onRowClick={(row) => { onRowClick={(row) => {
navigate(`/incidents/${row._id}`); navigate(`/incidents/${row.id}`);
}} }}
emptyViewPositive emptyViewPositive
emptyViewText={t("incidents.table.empty")} emptyViewText={t("incidents.table.empty")}
+2 -2
View File
@@ -12,7 +12,7 @@ import { useState, useEffect } from "react";
import { useGet } from "@/hooks/UseApi"; import { useGet } from "@/hooks/UseApi";
import type { ApiResponse } from "@/types/api"; import type { ApiResponse } from "@/types/api";
import type { SelectChangeEvent } from "@mui/material/Select"; 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 type { IMonitor } from "@/types/monitor";
import { config } from "@/config/index"; import { config } from "@/config/index";
@@ -31,7 +31,7 @@ const IncidentsPage = () => {
loading: incidentsLoading, loading: incidentsLoading,
isValidating: incidentsValidating, isValidating: incidentsValidating,
refetch, refetch,
} = useGet<ApiResponse<{ count: number; incidents: IIncident[] }>>( } = useGet<ApiResponse<{ count: number; incidents: IncidentWithDetails[] }>>(
`/incidents?page=${page}&rowsPerPage=${rowsPerPage}&range=${range}${ `/incidents?page=${page}&rowsPerPage=${rowsPerPage}&range=${range}${
selectedMonitorId && selectedMonitorId !== "all" selectedMonitorId && selectedMonitorId !== "all"
? `&monitorId=${selectedMonitorId}` ? `&monitorId=${selectedMonitorId}`
+28 -20
View File
@@ -1,4 +1,4 @@
import type { MonitorType } from "./monitor"; import type { MonitorType, MonitorStatus } from "./monitor";
export interface CheckTimingPhases { export interface CheckTimingPhases {
wait: number; wait: number;
@@ -11,7 +11,7 @@ export interface CheckTimingPhases {
total: number; total: number;
} }
export interface CheckTimings { export interface GotTimings {
start: string; start: string;
socket: string; socket: string;
lookup: string; lookup: string;
@@ -103,6 +103,12 @@ export interface INetInfo {
fifo_in: number; fifo_in: number;
fifo_out: number; fifo_out: number;
} }
export interface ICaptureInfo {
version?: string;
mode?: string;
}
export interface ICheck { export interface ICheck {
_id: string; _id: string;
metadata: { metadata: {
@@ -119,33 +125,35 @@ export interface ICheck {
expiry: string; expiry: string;
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
timings: CheckTimings; timings: GotTimings;
lighthouse?: ICheckLighthouseFields; lighthouse?: ICheckLighthouseFields;
system?: ISystemInfo; system?: ISystemInfo;
// Present for docker monitor checks // Present for docker monitor checks
dockerContainers?: IDockerContainerSummary[]; dockerContainers?: IDockerContainerSummary[];
} }
export interface CheckWithMonitor {
_id: string; export interface Check {
metadata: { id: string;
monitorId: { monitorId: string;
_id: string; teamId: string;
name: string; type: MonitorType;
}; status: MonitorStatus;
type: string; httpStatusCode?: number;
teamId: string;
};
status: string;
message: string; message: string;
responseTime: number; responseTime?: number;
normalResponseTime?: number; timings?: GotTimings;
httpStatusCode: number; errorMessage?: string;
ack: boolean; ackAt?: string;
expiry: string; ackBy?: string;
system?: ISystemInfo;
capture?: ICaptureInfo;
lighthouse?: ICheckLighthouseFields;
dockerContainers?: IDockerContainerSummary[];
createdAt: string; createdAt: string;
updatedAt: string; updatedAt: string;
timings: CheckTimings; expiry: string;
} }
export interface AggregateCheck { export interface AggregateCheck {
bucketDate: string; bucketDate: string;
+21 -9
View File
@@ -1,16 +1,28 @@
import type { IMongoUser } from "@/types/user"; export const ResolutionTypes = ["auto", "manual"] as const;
import type { IMonitor } from "@/types/monitor"; export type ResolutionType = (typeof ResolutionTypes)[number];
import type { MonitorType, MonitorStatus } from "@/types/monitor";
export interface IIncident { export interface Incident {
_id: string; id: string;
monitorId: IMonitor; monitorId: string;
teamId: string; teamId: string;
startedAt: string; startedAt: string;
startCheck: string; startCheck: string;
resolved: boolean;
endedAt?: string; endedAt?: string;
endCheck?: string; endCheck?: string;
resolvedBy?: IMongoUser; resolved: boolean;
resolutionType?: string; resolvedBy?: string;
resolutionType?: ResolutionType;
resolutionNote?: string; 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"; import mongoose, { Schema, Types } from "mongoose";
import type { ResolutionType } from "@/types/domain/index.js";
export const ResolutionTypes = ["auto", "manual"] as const; import { ResolutionTypes } from "@/types/domain/index.js";
export type ResolutionType = (typeof ResolutionTypes)[number];
export interface IIncident { export interface IIncident {
_id: Types.ObjectId; _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 { RecoveryToken } from "./recovery/RecoveryToken.js";
export type { IRecoveryToken } from "./recovery/RecoveryToken.js"; export type { IRecoveryToken } from "./recovery/RecoveryToken.js";
export { Incident, ResolutionTypes } from "./incidents/Incident.js"; export { Incident } from "./incidents/Incident.js";
export type { IIncident, ResolutionType } from "./incidents/Incident.js"; export type { IIncident } from "./incidents/Incident.js";
export { SystemSettings } from "./system/SystemSettings.js"; export { SystemSettings } from "./system/SystemSettings.js";
export type { ISystemSettings } from "./system/SystemSettings.js"; export type { ISystemSettings } from "./system/SystemSettings.js";
+3 -1
View File
@@ -37,6 +37,7 @@ import {
MongoMonitorRepository, MongoMonitorRepository,
MongoChecksRepository, MongoChecksRepository,
MongoMonitorStatsRepository, MongoMonitorStatsRepository,
MongoIncidentsRepository,
} from "@/repositories/index.js"; } from "@/repositories/index.js";
import type { CheckEntity } from "@/types/domain/index.js"; import type { CheckEntity } from "@/types/domain/index.js";
@@ -44,6 +45,7 @@ export const initServices = async () => {
const monitorRepository = new MongoMonitorRepository(); const monitorRepository = new MongoMonitorRepository();
const checksRepository = new MongoChecksRepository(); const checksRepository = new MongoChecksRepository();
const monitorStatsRepository = new MongoMonitorStatsRepository(); const monitorStatsRepository = new MongoMonitorStatsRepository();
const incidentsRepository = new MongoIncidentsRepository();
const checkService = new CheckService(checksRepository, monitorRepository); const checkService = new CheckService(checksRepository, monitorRepository);
const inviteService = new InviteService(); const inviteService = new InviteService();
@@ -72,7 +74,7 @@ export const initServices = async () => {
userService, userService,
settingsService settingsService
); );
const incidentService = new IncidentService(); const incidentService = new IncidentService(incidentsRepository);
const statsAggregationService = new StatsAggregationService(); const statsAggregationService = new StatsAggregationService();
const jobGenerator = new JobGenerator( const jobGenerator = new JobGenerator(
networkService, 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 type { IMonitorStatsRepository } from "@/repositories/monitor-stats/IMonitorStatsRepository.js";
export { default as MongoMonitorStatsRepository } from "@/repositories/monitor-stats/MongoMonitorStatsRepository.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, Monitor,
IUser, IUser,
} from "@/db/models/index.js"; } from "@/db/models/index.js";
import type { ResolutionType } from "@/db/models/index.js"; import type { ResolutionType } from "@/types/domain/index.js";
import mongoose from "mongoose";
import { getChildLogger } from "@/logger/Logger.js"; import { getChildLogger } from "@/logger/Logger.js";
import { ThresholdEvaluationResult } from "@/services/infrastructure/StatusService.js"; import { ThresholdEvaluationResult } from "@/services/infrastructure/StatusService.js";
import { getStartDate } from "@/utils/TimeUtils.js"; import { getStartDate } from "@/utils/TimeUtils.js";
import type { import type {
Monitor as MonitorEntity, Monitor as MonitorEntity,
CheckEntity, CheckEntity,
Incident as IncidentEntity,
IncidentWithDetails,
} from "@/types/domain/index.js"; } from "@/types/domain/index.js";
import type { IIncidentsRepository } from "@/repositories/index.js";
type IncidentPopulated = Omit<IIncident, "monitorId" | "resolvedBy"> & {
monitorId: IMonitor;
resolvedBy?: IUser | null;
};
export interface IIncidentService { export interface IIncidentService {
handleStatusChange: ( handleStatusChange: (
updatedMonitor: MonitorEntity, updatedMonitor: MonitorEntity,
lastCheck: CheckEntity lastCheck: CheckEntity
) => Promise<IIncident | null>; ) => Promise<IncidentEntity | null>;
handleThresholdBreach: ( handleThresholdBreach: (
updatedMonitor: MonitorEntity, updatedMonitor: MonitorEntity,
lastCheck: CheckEntity, lastCheck: CheckEntity,
evalResult: ThresholdEvaluationResult evalResult: ThresholdEvaluationResult
) => Promise<IIncident | null>; ) => Promise<IncidentEntity | null>;
create: ( create: (
teamId: mongoose.Types.ObjectId, teamId: string,
monitorId: mongoose.Types.ObjectId, monitorId: string,
startCheckId: mongoose.Types.ObjectId startCheckId: string
) => Promise<IIncident>; ) => Promise<IncidentEntity>;
get: (teamId: string, incidentId: string) => Promise<IIncident | null>; get: (
teamId: string,
incidentId: string
) => Promise<IncidentWithDetails | null>;
getAll: ( getAll: (
teamId: string, teamId: string,
monitorId: string, monitorId: string,
@@ -44,7 +44,7 @@ export interface IIncidentService {
range: string, range: string,
resolved?: boolean, resolved?: boolean,
resolutionType?: ResolutionType resolutionType?: ResolutionType
) => Promise<{ incidents: IIncident[]; count: number }>; ) => Promise<{ incidents: IncidentEntity[]; count: number }>;
resolve: ( resolve: (
teamId: string, teamId: string,
incidentId: string, incidentId: string,
@@ -52,11 +52,8 @@ export interface IIncidentService {
lastCheck?: CheckEntity, lastCheck?: CheckEntity,
resolvedBy?: string, resolvedBy?: string,
resolutionNote?: string resolutionNote?: string
) => Promise<IIncident | null>; ) => Promise<IncidentEntity | null>;
delete: ( delete: (teamId: string, incidentId: string) => Promise<boolean>;
teamId: mongoose.Types.ObjectId,
incidentId: mongoose.Types.ObjectId
) => Promise<boolean>;
export: (teamId: string) => Promise<Array<Record<string, unknown>>>; export: (teamId: string) => Promise<Array<Record<string, unknown>>>;
cleanupOrphanedIncidents: () => Promise<boolean>; cleanupOrphanedIncidents: () => Promise<boolean>;
} }
@@ -65,8 +62,10 @@ const SERVICE_NAME = "IncidentService";
const logger = getChildLogger(SERVICE_NAME); const logger = getChildLogger(SERVICE_NAME);
class IncidentService implements IIncidentService { class IncidentService implements IIncidentService {
public SERVICE_NAME: string; public SERVICE_NAME: string;
constructor() { private incidentsRepository: IIncidentsRepository;
constructor(incidentsRepository: IIncidentsRepository) {
this.SERVICE_NAME = SERVICE_NAME; this.SERVICE_NAME = SERVICE_NAME;
this.incidentsRepository = incidentsRepository;
} }
handleStatusChange = async ( handleStatusChange = async (
@@ -75,25 +74,27 @@ class IncidentService implements IIncidentService {
) => { ) => {
if (updatedMonitor.status === "down") { if (updatedMonitor.status === "down") {
const incident = await this.create( const incident = await this.create(
new mongoose.Types.ObjectId(updatedMonitor.teamId), updatedMonitor.teamId,
new mongoose.Types.ObjectId(updatedMonitor.id), updatedMonitor.id,
new mongoose.Types.ObjectId(lastCheck.id) lastCheck.id
); );
return incident; return incident;
} else if (updatedMonitor.status === "up") { } else if (updatedMonitor.status === "up") {
const incident = await Incident.findOne({ const incident =
monitorId: updatedMonitor.id, await this.incidentsRepository.findByMonitorIdAndResolved(
teamId: updatedMonitor.teamId, updatedMonitor.id,
resolved: false, updatedMonitor.teamId,
}); false
);
if (!incident) { if (!incident) {
return null; return null;
} }
const resolvedIncident = await this.resolve( const resolvedIncident = await this.resolve(
updatedMonitor.teamId.toString(), updatedMonitor.teamId,
incident._id.toString(), incident.id,
"auto", "auto",
lastCheck lastCheck
); );
@@ -107,42 +108,38 @@ class IncidentService implements IIncidentService {
lastCheck: CheckEntity, lastCheck: CheckEntity,
evalResult: ThresholdEvaluationResult evalResult: ThresholdEvaluationResult
) => { ) => {
const existing = await Incident.findOne({ const existing = await this.incidentsRepository.findByMonitorIdAndResolved(
monitorId: updatedMonitor.id, updatedMonitor.id,
teamId: updatedMonitor.teamId, updatedMonitor.teamId,
resolved: false, false
}); );
if (evalResult.hasBreach) { if (evalResult.hasBreach) {
if (!existing) { if (!existing) {
const incident = await this.create( const incident = await this.incidentsRepository.create({
new mongoose.Types.ObjectId(updatedMonitor.teamId), teamId: updatedMonitor.teamId,
new mongoose.Types.ObjectId(updatedMonitor.id), monitorId: updatedMonitor.id,
new mongoose.Types.ObjectId(lastCheck.id) startCheck: lastCheck.id,
); });
if (evalResult.notes.length) { if (evalResult.notes.length) {
await Incident.updateOne( await this.incidentsRepository.updateById(
{ _id: incident._id }, incident.id,
updatedMonitor.teamId,
{ {
$set: { resolutionNote: `threshold breach: ${evalResult.notes.join(
resolutionNote: `threshold breach: ${evalResult.notes.join( ", "
", " )}`,
)}`,
},
} }
); );
} }
return incident; return incident;
} }
if (evalResult.notes.length) { if (evalResult.notes.length) {
await Incident.updateOne( await this.incidentsRepository.updateById(
{ _id: existing._id }, 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) { } else if (existing) {
const resolved = await this.resolve( const resolved = await this.resolve(
updatedMonitor.teamId, updatedMonitor.teamId,
existing._id.toString(), existing.id,
"auto", "auto",
lastCheck lastCheck
); );
@@ -160,38 +157,32 @@ class IncidentService implements IIncidentService {
return null; return null;
}; };
create = async ( create = async (teamId: string, monitorId: string, startCheckId: string) => {
teamId: mongoose.Types.ObjectId, const existing = await this.incidentsRepository.findByMonitorIdAndResolved(
monitorId: mongoose.Types.ObjectId,
startCheckId: mongoose.Types.ObjectId
) => {
const existing = await Incident.findOne({
monitorId, monitorId,
teamId, teamId,
resolved: false, false
}); );
if (existing) { if (existing) {
return existing; return existing;
} }
let data: Partial<IIncident> = { let data: Partial<IncidentEntity> = {
teamId: new mongoose.Types.ObjectId(teamId), teamId,
monitorId: new mongoose.Types.ObjectId(monitorId), monitorId,
startedAt: new Date(), startCheck: startCheckId,
startCheck: new mongoose.Types.ObjectId(startCheckId),
}; };
const incident = await Incident.create(data); const incident = await this.incidentsRepository.create(data);
return incident; return incident;
}; };
get = async (teamId: string, incidentId: string) => { get = async (teamId: string, incidentId: string) => {
const incident = await Incident.findOne({ const incident =
_id: new mongoose.Types.ObjectId(incidentId), await this.incidentsRepository.findByIdWithMonitorAndResolvedBy(
teamId: new mongoose.Types.ObjectId(teamId), incidentId,
}) teamId
.populate("monitorId") );
.populate("resolvedBy");
return incident; return incident;
}; };
@@ -205,22 +196,24 @@ class IncidentService implements IIncidentService {
resolutionType?: ResolutionType resolutionType?: ResolutionType
) => { ) => {
const startDate = getStartDate(range); 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([ const [count, incidents] = await Promise.all([
Incident.countDocuments(match), this.incidentsRepository.count(
Incident.find(match) teamId,
.populate("monitorId") startDate,
.populate("resolvedBy") monitorId,
.sort({ createdAt: -1 }) resolved,
.skip(page * rowsPerPage) resolutionType
.limit(rowsPerPage), ),
this.incidentsRepository.findAllWithMonitorAndResolvedBy(
teamId,
page,
rowsPerPage,
startDate,
monitorId,
resolved,
resolutionType
),
]); ]);
return { count, incidents }; return { count, incidents };
}; };
@@ -233,53 +226,38 @@ class IncidentService implements IIncidentService {
resolvedBy?: string, resolvedBy?: string,
resolutionNote?: string resolutionNote?: string
) => { ) => {
const incident = await Incident.findOneAndUpdate( const resolvedIncident = await this.incidentsRepository.updateById(
{ _id: incidentId, teamId, resolved: false }, incidentId,
teamId,
{ {
$set: { resolved: true,
resolved: true, endedAt: new Date(),
endedAt: new Date(), endCheck: lastCheck ? lastCheck.id : undefined,
endCheck: lastCheck resolvedBy: resolvedBy ? resolvedBy : undefined,
? new mongoose.Types.ObjectId(lastCheck.id) resolutionType,
: undefined, resolutionNote: resolutionNote ? resolutionNote : undefined,
resolvedBy: resolvedBy ? resolvedBy : undefined, }
resolutionType,
resolutionNote: resolutionNote ? resolutionNote : undefined,
},
},
{ new: true }
); );
return incident; return resolvedIncident;
}; };
delete = async ( delete = async (teamId: string, incidentId: string) => {
teamId: mongoose.Types.ObjectId, return await this.incidentsRepository.deleteById(incidentId, teamId);
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;
}; };
export = async (teamId: string) => { export = async (teamId: string) => {
const incidents = await Incident.find({ const incidents = await this.incidentsRepository.findAllByTeamId(teamId);
teamId,
})
.populate("monitorId")
.populate("resolvedBy")
.lean<IncidentPopulated[]>();
return incidents.map((incident) => ({ return incidents.map((incident) => ({
monitor: incident.monitorId?.name ?? "", monitor: incident.monitor.name ?? "",
monitorId: incident.monitorId?._id?.toString?.() ?? "", monitorId: incident.monitor.id ?? "",
resolved: incident.resolved, resolved: incident.resolved,
resolutionType: incident.resolutionType ?? "Unresolved", resolutionType: incident.resolutionType ?? "Unresolved",
startedAt: incident.startedAt, startedAt: incident.startedAt,
endedAt: incident.endedAt ?? "Ongoing", 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 ApiError from "@/utils/ApiError.js";
import { getChildLogger } from "@/logger/Logger.js"; import { getChildLogger } from "@/logger/Logger.js";
import type { IEmailTransport } from "./NotificationServices/Email.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 SERVICE_NAME = "NotificationService";
const logger = getChildLogger(SERVICE_NAME); const logger = getChildLogger(SERVICE_NAME);
@@ -29,7 +32,7 @@ export interface ITestResult {
export interface INotificationService { export interface INotificationService {
handleNotifications: ( handleNotifications: (
monitor: MonitorEntity, monitor: MonitorEntity,
incident: IIncident incident: Incident
) => Promise<void>; ) => Promise<void>;
testNotificationChannels: ( testNotificationChannels: (
monitorId: string, monitorId: string,
@@ -58,7 +61,7 @@ class NotificationService implements INotificationService {
this.webhookService = new WebhookService(); this.webhookService = new WebhookService();
} }
handleNotifications = async (monitor: MonitorEntity, incident: IIncident) => { handleNotifications = async (monitor: MonitorEntity, incident: Incident) => {
const notificationIds = monitor.notificationChannels || []; const notificationIds = monitor.notificationChannels || [];
if (notificationIds.length === 0) { if (notificationIds.length === 0) {
@@ -89,7 +92,7 @@ class NotificationService implements INotificationService {
private sendForChannel = async ( private sendForChannel = async (
channel: INotificationChannel, channel: INotificationChannel,
monitor: MonitorEntity, monitor: MonitorEntity,
incident: IIncident incident: Incident
): Promise<boolean> => { ): Promise<boolean> => {
try { try {
switch (channel.type) { switch (channel.type) {
@@ -1,5 +1,5 @@
import { INotificationChannel, IIncident } from "@/db/models/index.js"; import { INotificationChannel } from "@/db/models/index.js";
import type { Monitor } from "@/types/domain/index.js"; import type { Monitor, Incident } from "@/types/domain/index.js";
import { IAlert, IMessageService } from "./IMessageService.js"; import { IAlert, IMessageService } from "./IMessageService.js";
import got from "got"; import got from "got";
import ApiError from "@/utils/ApiError.js"; 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 name = monitor?.name || "Unnamed monitor";
const monitorStatus = monitor?.status || "unknown status"; const monitorStatus = monitor?.status || "unknown status";
const url = monitor?.url || "no URL"; const url = monitor?.url || "no URL";
@@ -1,5 +1,5 @@
import { INotificationChannel, IIncident } from "@/db/models/index.js"; import { INotificationChannel } from "@/db/models/index.js";
import type { Monitor } from "@/types/domain/index.js"; import type { Monitor, Incident } from "@/types/domain/index.js";
import { IMessageService, IAlert } from "./IMessageService.js"; import { IMessageService, IAlert } from "./IMessageService.js";
import nodemailer, { Transporter } from "nodemailer"; 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 name = monitor?.name || "Unnamed monitor";
const monitorStatus = monitor?.status || "unknown status"; const monitorStatus = monitor?.status || "unknown status";
const url = monitor?.url || "no URL"; const url = monitor?.url || "no URL";
@@ -1,9 +1,9 @@
import { import { INotificationChannel } from "@/db/models/index.js";
INotificationChannel, import type {
IIncident, Monitor,
Incident,
ResolutionType, ResolutionType,
} from "@/db/models/index.js"; } from "@/types/domain/index.js";
import type { Monitor } from "@/types/domain/index.js";
export interface IAlert { export interface IAlert {
name: string; name: string;
@@ -18,7 +18,7 @@ export interface IAlert {
alertTime: Date; alertTime: Date;
} }
export interface IMessageService { export interface IMessageService {
buildAlert: (monitor: Monitor, incident: IIncident) => IAlert; buildAlert: (monitor: Monitor, incident: Incident) => IAlert;
sendMessage: ( sendMessage: (
alert: IAlert, alert: IAlert,
channel: INotificationChannel 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 { IAlert, IMessageService } from "./IMessageService.js";
import got from "got"; 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"; import { getChildLogger } from "@/logger/Logger.js";
const SERVICE_NAME = "SlackService"; 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 name = monitor?.name || "Unnamed monitor";
const monitorStatus = monitor?.status || "unknown status"; const monitorStatus = monitor?.status || "unknown status";
const url = monitor?.url || "no URL"; 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 { IAlert, IMessageService } from "./IMessageService.js";
import ApiError from "@/utils/ApiError.js"; import ApiError from "@/utils/ApiError.js";
import got from "got"; import got from "got";
import { getChildLogger } from "@/logger/Logger.js"; 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 SERVICE_NAME = "WebhookService";
const logger = getChildLogger(SERVICE_NAME); const logger = getChildLogger(SERVICE_NAME);
@@ -14,7 +14,7 @@ class WebhookService implements IMessageService {
this.SERVICE_NAME = SERVICE_NAME; this.SERVICE_NAME = SERVICE_NAME;
} }
buildAlert = (monitor: Monitor, incident: IIncident) => { buildAlert = (monitor: Monitor, incident: Incident) => {
const name = monitor?.name || "Unnamed monitor"; const name = monitor?.name || "Unnamed monitor";
const monitorStatus = monitor?.status || "unknown status"; const monitorStatus = monitor?.status || "unknown status";
const url = monitor?.url || "no URL"; 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/monitor.js";
export * from "@/types/domain/check.js"; export * from "@/types/domain/check.js";
export * from "@/types/domain/monitorStats.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 { z } from "zod";
import mongoose from "mongoose"; import mongoose from "mongoose";
import { ResolutionTypes } from "@/db/models/index.js"; import { ResolutionTypes } from "@/types/domain/index.js";
export const getIncidentQuerySchema = z.object({ export const getIncidentQuerySchema = z.object({
id: z.string().refine((val) => mongoose.Types.ObjectId.isValid(val), { 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 === undefined) return undefined;
if (val === "true") return true; if (val === "true") return true;
if (val === "false") return false; 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; return z.NEVER;
}), }),
page: z page: z
@@ -43,15 +46,24 @@ export const getIncidentsQuerySchema = z.object({
if (!val) return; if (!val) return;
const num = Number(val); const num = Number(val);
if (Number.isNaN(num)) { 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; return z.NEVER;
} }
if (num < 0) { 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; return z.NEVER;
} }
if (num > 100) { 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 z.NEVER;
} }
return num; return num;
@@ -68,4 +80,3 @@ export const getIncidentsQuerySchema = z.object({
export const patchIncidentsBodySchema = z.object({ export const patchIncidentsBodySchema = z.object({
resolutionNote: z.string().max(200).optional(), resolutionNote: z.string().max(200).optional(),
}); });