Files
Checkmate/server/src/services/business/IncidentService.ts
T

285 lines
7.4 KiB
TypeScript
Raw Normal View History

2025-11-21 20:18:34 +00:00
import {
IIncident,
Incident,
IMonitor,
Monitor,
ICheck,
} from "@/db/models/index.js";
2025-11-13 13:47:26 -08:00
import type { ResolutionType } from "@/db/models/index.js";
import mongoose from "mongoose";
import { getChildLogger } from "@/logger/Logger.js";
import ApiError from "@/utils/ApiError.js";
2025-12-05 22:46:46 +00:00
import { ThresholdEvaluationResult } from "@/services/infrastructure/StatusService.js";
2025-11-13 13:47:26 -08:00
export interface IIncidentService {
handleStatusChange: (
updatedMonitor: IMonitor,
lastCheck: ICheck
) => Promise<IIncident | null>;
2025-12-05 22:46:46 +00:00
handleThresholdBreach: (
updatedMonitor: IMonitor,
lastCheck: ICheck,
evalResult: ThresholdEvaluationResult
) => Promise<IIncident | null>;
2025-11-13 13:47:26 -08:00
create: (
teamId: mongoose.Types.ObjectId,
monitorId: mongoose.Types.ObjectId,
startCheckId: mongoose.Types.ObjectId
) => Promise<IIncident>;
2025-12-07 04:38:37 +00:00
get: (teamId: string, incidentId: string) => Promise<IIncident | null>;
2025-11-13 13:47:26 -08:00
getAll: (
teamId: string,
monitorId: string,
page: number,
rowsPerPage: number,
range: string,
resolved?: boolean,
resolutionType?: ResolutionType
) => Promise<{ incidents: IIncident[]; count: number }>;
resolve: (
teamId: string,
incidentId: string,
resolutionType: ResolutionType,
lastCheck?: ICheck,
resolvedBy?: string,
resolutionNote?: string
) => Promise<IIncident | null>;
delete: (
teamId: mongoose.Types.ObjectId,
incidentId: mongoose.Types.ObjectId
) => Promise<boolean>;
2025-11-21 20:18:34 +00:00
cleanupOrphanedIncidents: () => Promise<boolean>;
2025-11-13 13:47:26 -08:00
}
const SERVICE_NAME = "IncidentService";
2025-11-21 20:18:34 +00:00
const logger = getChildLogger(SERVICE_NAME);
2025-11-13 13:47:26 -08:00
class IncidentService implements IIncidentService {
public SERVICE_NAME: string;
constructor() {
this.SERVICE_NAME = SERVICE_NAME;
}
private getStartDate(range: string): Date {
const now = new Date();
switch (range) {
2025-12-08 02:29:52 +00:00
case "all":
return new Date(0);
2025-11-13 13:47:26 -08:00
case "2h":
return new Date(now.getTime() - 2 * 60 * 60 * 1000);
case "24h":
return new Date(now.getTime() - 24 * 60 * 60 * 1000);
case "7d":
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
case "30d":
return new Date(now.getTime() - 30 * 24 * 60 * 60 * 1000);
default:
throw new ApiError("Invalid range parameter", 400);
}
}
handleStatusChange = async (updatedMonitor: IMonitor, lastCheck: ICheck) => {
if (updatedMonitor.status === "down") {
const incident = await this.create(
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,
});
if (!incident) {
return null;
}
const resolvedIncident = await this.resolve(
updatedMonitor.teamId.toString(),
incident._id.toString(),
"auto",
lastCheck
);
return resolvedIncident;
}
return null;
};
2025-12-05 22:46:46 +00:00
handleThresholdBreach = async (
updatedMonitor: IMonitor,
lastCheck: ICheck,
evalResult: ThresholdEvaluationResult
) => {
const existing = await Incident.findOne({
monitorId: updatedMonitor._id,
teamId: updatedMonitor.teamId,
resolved: false,
});
if (evalResult.hasBreach) {
if (!existing) {
const incident = await this.create(
updatedMonitor.teamId,
updatedMonitor._id,
lastCheck._id
);
if (evalResult.notes.length) {
await Incident.updateOne(
{ _id: incident._id },
{
$set: {
resolutionNote: `threshold breach: ${evalResult.notes.join(
", "
)}`,
},
}
);
}
return incident;
}
if (evalResult.notes.length) {
await Incident.updateOne(
{ _id: existing._id },
{
$set: {
resolutionNote: `threshold breach: ${evalResult.notes.join(
", "
)}`,
},
}
);
}
return existing;
} else if (existing) {
const resolved = await this.resolve(
updatedMonitor.teamId.toString(),
existing._id.toString(),
"auto",
lastCheck
);
return resolved;
}
return null;
};
2025-11-13 13:47:26 -08:00
create = async (
teamId: mongoose.Types.ObjectId,
monitorId: mongoose.Types.ObjectId,
startCheckId: mongoose.Types.ObjectId
) => {
const existing = await Incident.findOne({
monitorId,
teamId,
resolved: 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),
};
const incident = await Incident.create(data);
return incident;
};
2025-12-07 04:38:37 +00:00
get = async (teamId: string, incidentId: string) => {
2025-11-13 13:47:26 -08:00
const incident = await Incident.findOne({
_id: new mongoose.Types.ObjectId(incidentId),
teamId: new mongoose.Types.ObjectId(teamId),
})
.populate("monitorId")
.populate("resolvedBy");
return incident;
};
getAll = async (
teamId: string,
monitorId: string,
page: number,
rowsPerPage: number,
range: string,
resolved?: boolean,
resolutionType?: ResolutionType
) => {
const startDate = this.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),
]);
return { count, incidents };
};
resolve = async (
teamId: string,
incidentId: string,
resolutionType: ResolutionType,
lastCheck?: ICheck,
resolvedBy?: string,
resolutionNote?: string
) => {
const incident = await Incident.findOneAndUpdate(
{ _id: incidentId, teamId, resolved: false },
{
$set: {
resolved: true,
endedAt: new Date(),
endCheck: lastCheck ? lastCheck._id : undefined,
resolvedBy: resolvedBy ? resolvedBy : undefined,
resolutionType,
resolutionNote: resolutionNote ? resolutionNote : undefined,
},
},
{ new: true }
);
return incident;
};
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;
};
2025-11-21 20:18:34 +00:00
async cleanupOrphanedIncidents() {
try {
const monitorIds = await Monitor.find().distinct("_id");
const result = await Incident.deleteMany({
monitorId: { $nin: monitorIds },
});
logger.info(`Deleted ${result.deletedCount} orphaned Incidents.`);
return true;
} catch (error) {
logger.error("Error cleaning up orphaned Incidents:", error);
return false;
}
}
2025-11-13 13:47:26 -08:00
}
export default IncidentService;