Files
Checkmate/server/src/domain/incidents/incident.service.ts
T

263 lines
8.6 KiB
TypeScript
Raw Normal View History

const SERVICE_NAME = "incidentService";
import type { Monitor } from "@/domain/monitors/monitor.type.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-02-25 20:13:07 +00:00
import { getDateForRange } from "@/utils/dataUtils.js";
2026-06-09 12:34:15 -07:00
import type { IIncidentsRepository } from "@/domain/incidents/incident.repository.interface.js";
import type { IMonitorsRepository } from "@/domain/monitors/monitor.repository.interface.js";
import type { IUsersRepository } from "@/domain/users/user.repository.interface.js";
import type { Incident, IncidentSummary } from "@/domain/incidents/incident.type.js";
import type { User } from "@/domain/users/user.type.js";
2026-06-10 09:30:14 -07:00
import type { MonitorActionDecision } from "@/worker/worker.helper.js";
2026-06-09 12:34:15 -07:00
import type { INotificationMessageBuilder } from "@/domain/notifications/notification.message-builder.js";
2026-02-24 19:19:32 +00:00
import type { ILogger } from "@/utils/logger.js";
import { DateRange } from "@/types/query.js";
2026-03-05 14:46:28 -08:00
export interface IIncidentService {
handleIncident(
monitor: Monitor,
code: number,
decision: MonitorActionDecision,
monitorStatusResponse?: MonitorStatusResponse
): Promise<Incident | null>;
resolveIncident(incidentId: string, userId: string, teamId: string, comment?: string, userEmail?: string): Promise<Incident>;
getIncidentsByTeam(
teamId: string,
sortOrder: string,
dateRange: DateRange,
2026-03-11 11:10:38 -07:00
page: number,
rowsPerPage: number,
status: boolean | undefined,
monitorId: string | undefined,
resolutionType: string | undefined
2026-03-05 14:46:28 -08:00
): Promise<{ incidents: Incident[]; count: number }>;
2026-03-11 11:10:38 -07:00
getIncidentSummary(teamId: string, limit?: number): Promise<IncidentSummary>;
2026-03-05 14:46:28 -08:00
getIncidentById(incidentId: string, teamId: string): Promise<{ incident: Incident; monitor: Monitor; user: User | null }>;
}
export class IncidentService implements IIncidentService {
static SERVICE_NAME = SERVICE_NAME;
2026-02-24 19:19:32 +00:00
private logger: ILogger;
2026-01-19 23:41:24 +00:00
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
2026-02-24 19:19:32 +00:00
constructor(
logger: ILogger,
incidentsRepository: IIncidentsRepository,
monitorsRepository: IMonitorsRepository,
usersRepository: IUsersRepository,
notificationMessageBuilder: INotificationMessageBuilder
) {
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;
}
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-04-08 10:43:47 -07:00
if (!decision.shouldResolveIncident || !activeIncident) {
return null;
}
2026-02-15 18:09:21 +00:00
2026-04-08 10:43:47 -07:00
activeIncident.status = false;
activeIncident.endTime = Date.now().toString();
activeIncident.resolutionType = "automatic";
return await this.incidentsRepository.updateById(activeIncident.id, activeIncident.teamId, activeIncident);
};
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-02-24 19:19:32 +00:00
details: { incidentId: resolvedIncident.id },
});
return resolvedIncident;
2026-03-11 11:10:38 -07:00
} catch (error: unknown) {
this.logger.error({
2026-01-19 23:41:24 +00:00
service: SERVICE_NAME,
method: "resolveIncident",
2026-03-11 11:10:38 -07:00
message: error instanceof Error ? error.message : "Unknown error",
2026-02-24 19:19:32 +00:00
details: { id: incidentId },
2026-03-11 11:10:38 -07:00
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
};
2026-01-21 10:15:13 -08:00
getIncidentsByTeam = async (
teamId: string,
sortOrder: string,
dateRange: DateRange,
2026-03-11 11:10:38 -07:00
page: number,
rowsPerPage: number,
status: boolean | undefined,
monitorId: string | undefined,
resolutionType: string | undefined
2026-01-21 10:15:13 -08:00
) => {
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-02-25 20:13:07 +00:00
const startDate = getDateForRange(dateRange);
2026-01-20 00:02:27 +00:00
2026-03-11 11:10:38 -07:00
const parsedPage = page ?? 0;
const parsedRowsPerPage = rowsPerPage ?? 20;
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-03-11 11:10:38 -07:00
status,
monitorId,
2026-01-20 00:02:27 +00:00
resolutionType
);
2026-03-11 11:14:44 -07:00
const count = await this.incidentsRepository.countByTeamId(teamId, startDate, status, monitorId, resolutionType);
2026-01-20 18:56:06 +00:00
return { incidents, count };
2026-03-11 11:10:38 -07:00
} catch (error: unknown) {
this.logger.error({
2026-01-19 23:41:24 +00:00
service: SERVICE_NAME,
method: "getIncidentsByTeam",
2026-03-11 11:10:38 -07:00
message: error instanceof Error ? error.message : "Unknown error",
2026-02-24 19:19:32 +00:00
details: { teamId },
2026-03-11 11:10:38 -07:00
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
};
2026-03-11 11:10:38 -07:00
getIncidentSummary = async (teamId: string, limit?: number) => {
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-03-11 11:10:38 -07:00
const parsedLimit = limit ?? 10;
2026-01-20 18:56:06 +00:00
const summary = await this.incidentsRepository.findSummaryByTeamId(teamId, parsedLimit);
return summary;
2026-03-11 11:10:38 -07:00
} catch (error: unknown) {
this.logger.error({
2026-01-19 23:41:24 +00:00
service: SERVICE_NAME,
method: "getIncidentSummary",
2026-03-11 11:10:38 -07:00
message: error instanceof Error ? error.message : "Unknown error",
2026-02-24 19:19:32 +00:00
details: { teamId },
2026-03-11 11:10:38 -07:00
stack: error instanceof Error ? error.stack : undefined,
});
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-03-11 11:10:38 -07:00
} catch (error: unknown) {
this.logger.error({
2026-01-19 23:41:24 +00:00
service: SERVICE_NAME,
method: "getIncidentById",
2026-03-11 11:10:38 -07:00
message: error instanceof Error ? error.message : "Unknown error",
2026-02-24 19:19:32 +00:00
details: { incidentId },
2026-03-11 11:10:38 -07:00
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
};
}