Files
Checkmate/server/src/service/business/incidentService.ts
T

261 lines
7.9 KiB
TypeScript
Raw Normal View History

const SERVICE_NAME = "incidentService";
2026-01-19 23:41:24 +00:00
import type { Monitor } from "@/types/monitor.js";
2026-02-17 17:42:11 +00:00
import type { MonitorStatusResponse } from "@/types/network.js";
2026-01-19 23:41:24 +00:00
import { AppError } from "@/utils/AppError.js";
2026-01-20 18:56:06 +00:00
import { ParseBoolean } from "@/utils/utils.js";
2026-01-22 21:28:28 +00:00
import type { IIncidentsRepository, IMonitorsRepository, IUsersRepository } from "@/repositories/index.js";
2026-01-19 23:41:24 +00:00
import type { Incident } from "@/types/index.js";
2026-02-15 18:09:21 +00:00
import type { MonitorActionDecision } from "@/service/infrastructure/SuperSimpleQueue/SuperSimpleQueueHelper.js";
2026-02-17 17:49:56 +00:00
import type { INotificationMessageBuilder } from "@/service/infrastructure/notificationMessageBuilder.js";
2026-01-20 00:02:27 +00:00
const dateRangeLookup: Record<string, Date | undefined> = {
2026-01-31 01:32:33 +00:00
recent: new Date(new Date().setHours(new Date().getHours() - 2)),
2026-01-20 00:02:27 +00:00
hour: new Date(new Date().setHours(new Date().getHours() - 1)),
day: new Date(new Date().setDate(new Date().getDate() - 1)),
week: new Date(new Date().setDate(new Date().getDate() - 7)),
month: new Date(new Date().setMonth(new Date().getMonth() - 1)),
all: undefined,
};
class IncidentService {
static SERVICE_NAME = SERVICE_NAME;
2026-01-19 23:41:24 +00:00
private logger: any;
private incidentsRepository: IIncidentsRepository;
2026-01-22 21:28:28 +00:00
private monitorsRepository: IMonitorsRepository;
private usersRepository: IUsersRepository;
2026-02-17 17:49:56 +00:00
private notificationMessageBuilder: INotificationMessageBuilder;
2026-01-19 23:41:24 +00:00
constructor({
logger,
incidentsRepository,
2026-01-22 21:28:28 +00:00
monitorsRepository,
usersRepository,
2026-02-17 17:49:56 +00:00
notificationMessageBuilder,
2026-01-19 23:41:24 +00:00
}: {
logger: any;
incidentsRepository: IIncidentsRepository;
2026-01-22 21:28:28 +00:00
monitorsRepository: IMonitorsRepository;
usersRepository: IUsersRepository;
2026-02-17 17:49:56 +00:00
notificationMessageBuilder: INotificationMessageBuilder;
2026-01-19 23:41:24 +00:00
}) {
this.logger = logger;
2026-01-19 23:41:24 +00:00
this.incidentsRepository = incidentsRepository;
2026-01-22 21:28:28 +00:00
this.monitorsRepository = monitorsRepository;
this.usersRepository = usersRepository;
2026-02-17 17:49:56 +00:00
this.notificationMessageBuilder = notificationMessageBuilder;
}
get serviceName() {
return IncidentService.SERVICE_NAME;
}
2026-02-17 17:42:11 +00:00
handleIncident = async (
monitor: Monitor,
code: number,
decision: MonitorActionDecision,
monitorStatusResponse?: MonitorStatusResponse
): Promise<Incident | null> => {
2026-02-15 18:09:21 +00:00
if (!decision.shouldCreateIncident && !decision.shouldResolveIncident) {
return null;
}
2026-01-19 23:41:24 +00:00
const activeIncident = await this.incidentsRepository.findActiveByMonitorId(monitor.id, monitor.teamId);
2026-02-15 18:09:21 +00:00
if (decision.shouldCreateIncident) {
if (activeIncident) {
return activeIncident;
2026-01-19 23:41:24 +00:00
} else {
2026-02-17 17:42:11 +00:00
let statusCode = code;
let message: string | undefined;
// For threshold breaches, use 9999 status code and build descriptive message
if (decision.incidentReason === "threshold_breach") {
statusCode = 9999;
message = this.buildThresholdBreachMessage(monitor, monitorStatusResponse);
}
2026-01-19 23:41:24 +00:00
const incident = {
monitorId: monitor.id,
teamId: monitor.teamId,
startTime: Date.now().toString(),
status: true,
2026-02-17 17:42:11 +00:00
statusCode,
message,
2026-01-19 23:41:24 +00:00
};
return await this.incidentsRepository.create(incident);
}
}
2026-02-15 18:09:21 +00:00
if (decision.shouldResolveIncident) {
if (!activeIncident) {
return null;
}
activeIncident.status = false;
activeIncident.endTime = Date.now().toString();
activeIncident.resolutionType = "automatic";
return await this.incidentsRepository.updateById(activeIncident.id, activeIncident.teamId, activeIncident);
}
2026-02-15 18:09:21 +00:00
return null;
};
2026-02-17 17:42:11 +00:00
private buildThresholdBreachMessage(monitor: Monitor, monitorStatusResponse?: MonitorStatusResponse): string {
2026-02-17 17:49:56 +00:00
if (!monitorStatusResponse) {
2026-02-17 17:42:11 +00:00
return "Threshold breach detected";
}
2026-02-17 17:49:56 +00:00
const breaches = this.notificationMessageBuilder.extractThresholdBreaches(monitor, monitorStatusResponse);
2026-02-17 17:42:11 +00:00
if (breaches.length === 0) {
return "Threshold breach detected";
}
2026-02-17 17:49:56 +00:00
return breaches.map((b) => `${b.metric.toUpperCase()}: ${b.formattedValue} (threshold: ${b.threshold}${b.unit})`).join(", ");
2026-02-17 17:42:11 +00:00
}
2026-02-02 06:08:51 +00:00
resolveIncident = async (incidentId: string, userId: string, teamId: string, comment?: string, userEmail?: string) => {
try {
if (!incidentId) {
2026-01-19 23:41:24 +00:00
throw new AppError({ message: "No incident ID in request", service: SERVICE_NAME, method: "resolveIncident" });
}
if (!userId) {
2026-01-19 23:41:24 +00:00
throw new AppError({ message: "No user ID in request", service: SERVICE_NAME, method: "resolveIncident" });
}
if (!teamId) {
2026-01-19 23:41:24 +00:00
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "resolveIncident" });
}
2026-01-19 23:41:24 +00:00
const incident = await this.incidentsRepository.findActiveByIncidentId(incidentId, teamId);
if (!incident) {
2026-01-19 23:41:24 +00:00
throw new AppError({ message: "Incident not found", service: SERVICE_NAME, method: "resolveIncident" });
}
2025-11-18 16:01:47 -05:00
if (incident.status === false) {
2026-01-19 23:41:24 +00:00
throw new AppError({ message: "Incident is already resolved", service: SERVICE_NAME, method: "resolveIncident" });
}
2026-01-19 23:41:24 +00:00
incident.resolutionType = "manual";
incident.status = false;
incident.resolvedBy = userId;
2026-02-02 06:08:51 +00:00
incident.resolvedByEmail = userEmail || null;
2026-01-19 23:41:24 +00:00
incident.comment = comment || null;
incident.endTime = Date.now().toString();
2026-01-19 23:41:24 +00:00
const resolvedIncident = await this.incidentsRepository.updateById(incident.id, teamId, incident);
this.logger.debug({
service: SERVICE_NAME,
method: "resolveIncidentManually",
message: `Incident manually resolved by user`,
2026-01-19 23:41:24 +00:00
details: resolvedIncident.id,
});
return resolvedIncident;
2026-01-19 23:41:24 +00:00
} catch (error: any) {
this.logger.error({
2026-01-19 23:41:24 +00:00
service: SERVICE_NAME,
method: "resolveIncident",
message: error.message,
2026-01-19 23:41:24 +00:00
details: incidentId,
stack: error.stack,
});
throw error;
}
};
2026-01-21 10:15:13 -08:00
getIncidentsByTeam = async (
teamId: string,
sortOrder: string,
dateRange: string,
page: string,
rowsPerPage: string,
status: string,
monitorId: string,
resolutionType: string
) => {
try {
if (!teamId) {
2026-01-22 21:49:49 +00:00
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getIncidentsByTeam", status: 400 });
}
2026-01-20 00:02:27 +00:00
const startDate = dateRangeLookup[dateRange];
const parsedPage = Number.isFinite(parseInt(page)) ? parseInt(page) : 0;
const parsedRowsPerPage = Number.isFinite(parseInt(rowsPerPage)) ? parseInt(rowsPerPage) : 20;
2026-01-20 18:56:06 +00:00
const parsedStatus = typeof status === "undefined" ? undefined : ParseBoolean(status);
2026-01-20 00:02:27 +00:00
2026-01-20 18:56:06 +00:00
const incidents = await this.incidentsRepository.findByTeamId(
teamId,
2026-01-20 00:02:27 +00:00
startDate,
parsedPage,
parsedRowsPerPage,
sortOrder,
2026-01-20 00:02:27 +00:00
parsedStatus,
monitorId,
2026-01-20 00:02:27 +00:00
resolutionType
);
2026-01-20 18:56:06 +00:00
const count = await this.incidentsRepository.countByTeamId(teamId, startDate, parsedStatus, monitorId, resolutionType);
return { incidents, count };
2026-01-19 23:41:24 +00:00
} catch (error: any) {
this.logger.error({
2026-01-19 23:41:24 +00:00
service: SERVICE_NAME,
method: "getIncidentsByTeam",
message: error.message,
2026-01-19 23:41:24 +00:00
details: teamId,
stack: error.stack,
});
throw error;
}
};
2026-01-20 18:56:06 +00:00
getIncidentSummary = async (teamId: string, limit?: string) => {
try {
if (!teamId) {
2026-01-22 21:49:49 +00:00
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getIncidentSummary", status: 400 });
}
2026-01-20 18:56:06 +00:00
const parsedLimit = limit && Number.isFinite(parseInt(limit, 10)) ? parseInt(limit, 10) : 10;
const summary = await this.incidentsRepository.findSummaryByTeamId(teamId, parsedLimit);
return summary;
2026-01-19 23:41:24 +00:00
} catch (error: any) {
this.logger.error({
2026-01-19 23:41:24 +00:00
service: SERVICE_NAME,
method: "getIncidentSummary",
message: error.message,
2026-01-19 23:41:24 +00:00
details: teamId,
stack: error.stack,
});
throw error;
}
};
2026-01-22 21:28:28 +00:00
getIncidentById = async (incidentId: string, teamId: string) => {
try {
2026-01-22 21:28:28 +00:00
const incident = await this.incidentsRepository.findById(incidentId, teamId);
const monitor = await this.monitorsRepository.findById(incident.monitorId, teamId);
let user = null;
if (incident.resolvedBy) {
user = await this.usersRepository.findById(incident.resolvedBy);
}
2026-01-22 21:28:28 +00:00
return { incident, monitor, user };
2026-01-19 23:41:24 +00:00
} catch (error: any) {
this.logger.error({
2026-01-19 23:41:24 +00:00
service: SERVICE_NAME,
method: "getIncidentById",
message: error.message,
2026-01-19 23:41:24 +00:00
details: incidentId,
stack: error.stack,
});
throw error;
}
};
}
export default IncidentService;