import { IIncident, Incident, IMonitor, Monitor, ICheck, IUser, } from "@/db/models/index.js"; import type { ResolutionType } from "@/db/models/index.js"; import mongoose from "mongoose"; import { getChildLogger } from "@/logger/Logger.js"; import { ThresholdEvaluationResult } from "@/services/infrastructure/StatusService.js"; import { getStartDate } from "@/utils/TimeUtils.js"; type IncidentPopulated = Omit & { monitorId: IMonitor; resolvedBy?: IUser | null; }; export interface IIncidentService { handleStatusChange: ( updatedMonitor: IMonitor, lastCheck: ICheck ) => Promise; handleThresholdBreach: ( updatedMonitor: IMonitor, lastCheck: ICheck, evalResult: ThresholdEvaluationResult ) => Promise; create: ( teamId: mongoose.Types.ObjectId, monitorId: mongoose.Types.ObjectId, startCheckId: mongoose.Types.ObjectId ) => Promise; get: (teamId: string, incidentId: string) => Promise; 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; delete: ( teamId: mongoose.Types.ObjectId, incidentId: mongoose.Types.ObjectId ) => Promise; export: (teamId: string) => Promise>>; cleanupOrphanedIncidents: () => Promise; } const SERVICE_NAME = "IncidentService"; const logger = getChildLogger(SERVICE_NAME); class IncidentService implements IIncidentService { public SERVICE_NAME: string; constructor() { this.SERVICE_NAME = SERVICE_NAME; } 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; }; 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; }; 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 = { 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; }; 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"); return incident; }; getAll = async ( teamId: string, monitorId: string, page: number, rowsPerPage: number, range: string, resolved?: boolean, 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), ]); 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; }; export = async (teamId: string) => { const incidents = await Incident.find({ teamId, }) .populate("monitorId") .populate("resolvedBy") .lean(); return incidents.map((incident) => ({ monitor: incident.monitorId?.name ?? "", monitorId: incident.monitorId?._id?.toString?.() ?? "", resolved: incident.resolved, resolutionType: incident.resolutionType ?? "Unresolved", startedAt: incident.startedAt, endedAt: incident.endedAt ?? "Ongoing", resolvedBy: incident.resolvedBy ? incident.resolvedBy.email ?? "" : "", })); }; 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; } } } export default IncidentService;