reorg to domain and api

This commit is contained in:
Alex Holliday committed 2026-06-09 12:34:15 -07:00
1 parent 0fb210e9e1
commit d022f7d849
190 files changed
+643 -830

No files matched your search

@@ -0,0 +1,90 @@
import { Schema, model, type Types } from "mongoose";
import { IncidentResolutionTypes, type Incident } from "@/domain/incidents/incident.type.js";
type IncidentDocumentBase = Omit<Incident, "id" | "monitorId" | "teamId" | "resolvedBy" | "startTime" | "endTime" | "createdAt" | "updatedAt"> & {
monitorId: Types.ObjectId;
teamId: Types.ObjectId;
resolvedBy?: Types.ObjectId | null;
startTime: Date;
endTime: Date | null;
createdAt: Date;
updatedAt: Date;
};
export interface IncidentDocument extends IncidentDocumentBase {
_id: Types.ObjectId;
}
const IncidentSchema = new Schema<IncidentDocument>(
{
monitorId: {
type: Schema.Types.ObjectId,
ref: "Monitor",
required: true,
immutable: true,
index: true,
},
teamId: {
type: Schema.Types.ObjectId,
ref: "Team",
required: true,
immutable: true,
index: true,
},
startTime: {
type: Date,
immutable: true,
required: true,
},
endTime: {
type: Date,
default: null,
},
status: {
type: Boolean,
default: true,
index: true,
},
message: {
type: String,
default: null,
},
statusCode: {
type: Number,
default: null,
index: true,
},
resolutionType: {
type: String,
enum: IncidentResolutionTypes,
default: null,
},
resolvedBy: {
type: Schema.Types.ObjectId,
ref: "User",
default: null,
},
resolvedByEmail: {
type: String,
default: null,
},
comment: {
type: String,
default: null,
},
},
{ timestamps: true }
);
IncidentSchema.index({ monitorId: 1, status: 1 });
IncidentSchema.index({ teamId: 1, status: 1 });
IncidentSchema.index({ teamId: 1, startTime: -1 });
IncidentSchema.index({ status: 1, startTime: -1 });
IncidentSchema.index({ resolutionType: 1, status: 1 });
IncidentSchema.index({ resolvedBy: 1, status: 1 });
IncidentSchema.index({ createdAt: -1 });
const IncidentModel = model<IncidentDocument>("Incident", IncidentSchema);
export { IncidentModel };
export default IncidentModel;
@@ -0,0 +1,29 @@
import type { Incident } from "@/domain/incidents/incident.type.js";
import type { IncidentSummary } from "@/domain/incidents/incident.type.js";
export interface IIncidentsRepository {
// create
create(incident: Partial<Incident>): Promise<Incident>;
// fetch
findById(incidentId: string, teamId: string): Promise<Incident>;
findActiveByIncidentId(incidentId: string, teamId: string): Promise<Incident | null>;
findActiveByMonitorId(monitorId: string, teamId: string): Promise<Incident | null>;
findByTeamId(
teamId: string,
startDate: Date | undefined,
page: number,
rowsPerPage: number,
sortOrder?: string,
status?: boolean,
monitorId?: string,
resolutionType?: string
): Promise<Incident[]>;
findSummaryByTeamId(teamId: string, limit?: number): Promise<IncidentSummary>;
countByTeamId(teamId: string, startDate: Date | undefined, status?: boolean, monitorId?: string, resolutionType?: string): Promise<number>;
// update
updateById(incidentId: string, teamId: string, updateData: Partial<Incident>): Promise<Incident>;
// delete
deleteByMonitorId(monitorId: string, teamId: string): Promise<number>;
deleteByMonitorIdsNotIn(monitorIds: string[]): Promise<number>;
// other
}
@@ -0,0 +1,291 @@
import { IncidentModel } from "@/domain/incidents/incident.model.js";
import type { IncidentDocument } from "@/domain/incidents/incident.model.js";
import type { Incident, IncidentSummary } from "@/domain/incidents/incident.type.js";
import type { IIncidentsRepository } from "@/domain/incidents/incident.repository.interface.js";
import mongoose from "mongoose";
import { AppError } from "@/utils/AppError.js";
class MongoIncidentsRepository implements IIncidentsRepository {
private toStringId = (value?: mongoose.Types.ObjectId | string | null): string => {
if (!value) {
return "";
}
return value instanceof mongoose.Types.ObjectId ? value.toString() : String(value);
};
private toDateString = (value?: Date | string | null): string => {
if (!value) {
return new Date(0).toISOString();
}
return value instanceof Date ? value.toISOString() : new Date(value).toISOString();
};
private buildMatchStage({
teamId,
startDate,
status,
monitorId,
resolutionType,
}: {
teamId: string;
startDate: Date | undefined;
status?: boolean;
monitorId?: string;
resolutionType?: string;
}): Record<string, unknown> {
const matchStage: Record<string, unknown> = {
teamId: new mongoose.Types.ObjectId(teamId),
...(status !== undefined && { status }),
...(monitorId && { monitorId: new mongoose.Types.ObjectId(monitorId) }),
...(resolutionType && { resolutionType }),
};
if (startDate) {
matchStage.createdAt = { $gte: startDate };
}
return matchStage;
}
protected toEntity = (doc: IncidentDocument): Incident => {
return {
id: this.toStringId(doc._id),
monitorId: this.toStringId(doc.monitorId),
teamId: this.toStringId(doc.teamId),
startTime: this.toDateString(doc.startTime),
endTime: doc.endTime ? this.toDateString(doc.endTime) : null,
status: doc.status,
message: doc.message ?? null,
statusCode: doc.statusCode ?? null,
resolutionType: doc.resolutionType ?? null,
resolvedBy: doc.resolvedBy ? this.toStringId(doc.resolvedBy) : null,
resolvedByEmail: doc.resolvedByEmail ?? null,
comment: doc.comment ?? null,
createdAt: this.toDateString(doc.createdAt),
updatedAt: this.toDateString(doc.updatedAt),
};
};
protected mapDocuments = (documents: IncidentDocument[] | IncidentDocument | null): Incident[] => {
if (!documents) {
return [];
}
if (Array.isArray(documents)) {
return documents.map((doc) => this.toEntity(doc));
}
return [this.toEntity(documents)];
};
async create(incident: Partial<Incident>): Promise<Incident> {
const newIncident = await IncidentModel.create(incident);
return this.toEntity(newIncident);
}
findById = async (incidentId: string, teamId: string): Promise<Incident> => {
const incident = await IncidentModel.findOne({
_id: new mongoose.Types.ObjectId(incidentId),
teamId: new mongoose.Types.ObjectId(teamId),
});
if (!incident) {
throw new AppError({ message: `Incident with id ${incidentId} not found`, status: 404 });
}
return this.toEntity(incident);
};
findActiveByIncidentId = async (incidentId: string, teamId: string): Promise<Incident | null> => {
const incident = await IncidentModel.findOne({
_id: new mongoose.Types.ObjectId(incidentId),
teamId: new mongoose.Types.ObjectId(teamId),
status: true,
});
if (!incident) {
return null;
}
return this.toEntity(incident);
};
findActiveByMonitorId = async (monitorId: string, teamId: string): Promise<Incident | null> => {
const incident = await IncidentModel.findOne({
monitorId: new mongoose.Types.ObjectId(monitorId),
teamId: new mongoose.Types.ObjectId(teamId),
status: true,
});
if (!incident) {
return null;
}
return this.toEntity(incident);
};
findByTeamId = async (
teamId: string,
startDate: Date | undefined,
page: number,
rowsPerPage: number,
sortOrder?: string,
status?: boolean,
monitorId?: string,
resolutionType?: string
): Promise<Incident[]> => {
const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType });
const incidents = await IncidentModel.find(matchStage)
.sort({ createdAt: sortOrder === "asc" ? 1 : -1 })
.skip(page * rowsPerPage)
.limit(rowsPerPage);
return this.mapDocuments(incidents);
};
updateById = async (incidentId: string, teamId: string, patch: Partial<Incident>) => {
const updatedIncident = await IncidentModel.findOneAndUpdate(
{ _id: new mongoose.Types.ObjectId(incidentId), teamId: new mongoose.Types.ObjectId(teamId) },
{
$set: {
...patch,
},
},
{ new: true, runValidators: true }
);
if (!updatedIncident) {
throw new AppError({ message: `Failed to update incident with id ${incidentId}`, status: 500 });
}
return this.toEntity(updatedIncident);
};
countByTeamId = async (
teamId: string,
startDate: Date | undefined,
status?: boolean,
monitorId?: string,
resolutionType?: string
): Promise<number> => {
const matchStage = this.buildMatchStage({ teamId, startDate, status, monitorId, resolutionType });
return IncidentModel.countDocuments(matchStage);
};
findSummaryByTeamId = async (teamId: string, limit: number): Promise<IncidentSummary> => {
const matchStage = { teamId: new mongoose.Types.ObjectId(teamId) };
const counts = await IncidentModel.aggregate([
{ $match: matchStage },
{
$group: {
_id: "$status",
count: { $sum: 1 },
manualResolutions: {
$sum: { $cond: [{ $eq: ["$resolutionType", "manual"] }, 1, 0] },
},
automaticResolutions: {
$sum: { $cond: [{ $eq: ["$resolutionType", "automatic"] }, 1, 0] },
},
},
},
]);
let total = 0;
let active = 0;
let manual = 0;
let automatic = 0;
counts.forEach((item) => {
total += item.count;
if (item._id === true) {
active = item.count;
}
manual += item.manualResolutions;
automatic += item.automaticResolutions;
});
const resolutionTimeResult = await IncidentModel.aggregate([
{ $match: { ...matchStage, status: false, endTime: { $exists: true, $ne: null } } },
{ $project: { resolutionTime: { $subtract: ["$endTime", "$startTime"] } } },
{ $group: { _id: null, avgResolutionTime: { $avg: "$resolutionTime" } } },
]);
const avgResolutionTimeMs = resolutionTimeResult[0]?.avgResolutionTime || 0;
const avgResolutionTimeHours = Math.round((avgResolutionTimeMs / (1000 * 60 * 60) || 0) * 100) / 100;
const monitorResult = await IncidentModel.aggregate([
{ $match: matchStage },
{ $group: { _id: "$monitorId", count: { $sum: 1 } } },
{ $sort: { count: -1 } },
{ $limit: 1 },
{
$lookup: {
from: "monitors",
localField: "_id",
foreignField: "_id",
as: "monitor",
},
},
{ $project: { monitorId: "$_id", count: 1, monitorName: { $arrayElemAt: ["$monitor.name", 0] } } },
]);
const latestLimit = Math.max(1, Number.isFinite(Number(limit)) ? Number(limit) : 10);
const latestIncidents = await IncidentModel.aggregate([
{ $match: matchStage },
{ $sort: { createdAt: -1 } },
{ $limit: latestLimit },
{
$lookup: {
from: "monitors",
localField: "monitorId",
foreignField: "_id",
as: "monitor",
},
},
{
$project: {
_id: 1,
monitorId: 1,
monitorName: { $arrayElemAt: ["$monitor.name", 0] },
status: 1,
startTime: 1,
endTime: 1,
resolutionType: 1,
message: 1,
statusCode: 1,
createdAt: 1,
},
},
]);
return {
total,
totalActive: active,
totalManualResolutions: manual,
totalAutomaticResolutions: automatic,
avgResolutionTimeHours,
topMonitor: monitorResult[0]
? {
monitorId: this.toStringId(monitorResult[0].monitorId),
monitorName: monitorResult[0].monitorName ?? null,
incidentCount: monitorResult[0].count,
}
: null,
latestIncidents: latestIncidents.map((incident) => ({
id: this.toStringId(incident._id),
monitorId: this.toStringId(incident.monitorId),
monitorName: incident.monitorName ?? null,
status: incident.status,
startTime: this.toDateString(incident.startTime),
endTime: incident.endTime ? this.toDateString(incident.endTime) : null,
resolutionType: incident.resolutionType ?? null,
message: incident.message ?? null,
statusCode: incident.statusCode ?? null,
createdAt: this.toDateString(incident.createdAt),
})),
};
};
deleteByMonitorId = async (monitorId: string, teamId: string) => {
const result = await IncidentModel.deleteMany({
monitorId: new mongoose.Types.ObjectId(monitorId),
teamId: new mongoose.Types.ObjectId(teamId),
});
return result.deletedCount || 0;
};
deleteByMonitorIdsNotIn = async (monitorIds: string[]): Promise<number> => {
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
const result = await IncidentModel.deleteMany({ monitorId: { $nin: objectIds } });
return result.deletedCount ?? 0;
};
}
export default MongoIncidentsRepository;
@@ -0,0 +1,266 @@
const SERVICE_NAME = "incidentService";
import type { Monitor } from "@/domain/monitors/monitor.types.js";
import type { MonitorStatusResponse } from "@/types/network.js";
import { AppError } from "@/utils/AppError.js";
import { getDateForRange } from "@/utils/dataUtils.js";
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";
import type { MonitorActionDecision } from "@/service/job-queues/job-queue.helper.js";
import type { INotificationMessageBuilder } from "@/domain/notifications/notification.message-builder.js";
import type { ILogger } from "@/utils/logger.js";
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: string,
page: number,
rowsPerPage: number,
status: boolean | undefined,
monitorId: string | undefined,
resolutionType: string | undefined
): Promise<{ incidents: Incident[]; count: number }>;
getIncidentSummary(teamId: string, limit?: number): Promise<IncidentSummary>;
getIncidentById(incidentId: string, teamId: string): Promise<{ incident: Incident; monitor: Monitor; user: User | null }>;
}
export class IncidentService implements IIncidentService {
static SERVICE_NAME = SERVICE_NAME;
private logger: ILogger;
private incidentsRepository: IIncidentsRepository;
private monitorsRepository: IMonitorsRepository;
private usersRepository: IUsersRepository;
private notificationMessageBuilder: INotificationMessageBuilder;
constructor(
logger: ILogger,
incidentsRepository: IIncidentsRepository,
monitorsRepository: IMonitorsRepository,
usersRepository: IUsersRepository,
notificationMessageBuilder: INotificationMessageBuilder
) {
this.logger = logger;
this.incidentsRepository = incidentsRepository;
this.monitorsRepository = monitorsRepository;
this.usersRepository = usersRepository;
this.notificationMessageBuilder = notificationMessageBuilder;
}
get serviceName() {
return IncidentService.SERVICE_NAME;
}
handleIncident = async (
monitor: Monitor,
code: number,
decision: MonitorActionDecision,
monitorStatusResponse?: MonitorStatusResponse
): Promise<Incident | null> => {
if (!decision.shouldCreateIncident && !decision.shouldResolveIncident) {
return null;
}
const activeIncident = await this.incidentsRepository.findActiveByMonitorId(monitor.id, monitor.teamId);
if (decision.shouldCreateIncident) {
if (activeIncident) {
return activeIncident;
} else {
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);
}
const incident = {
monitorId: monitor.id,
teamId: monitor.teamId,
startTime: Date.now().toString(),
status: true,
statusCode,
message,
};
return await this.incidentsRepository.create(incident);
}
}
if (!decision.shouldResolveIncident || !activeIncident) {
return null;
}
activeIncident.status = false;
activeIncident.endTime = Date.now().toString();
activeIncident.resolutionType = "automatic";
return await this.incidentsRepository.updateById(activeIncident.id, activeIncident.teamId, activeIncident);
};
private buildThresholdBreachMessage(monitor: Monitor, monitorStatusResponse?: MonitorStatusResponse): string {
if (!monitorStatusResponse) {
return "Threshold breach detected";
}
const breaches = this.notificationMessageBuilder.extractThresholdBreaches(monitor, monitorStatusResponse);
if (breaches.length === 0) {
return "Threshold breach detected";
}
return breaches.map((b) => `${b.metric.toUpperCase()}: ${b.formattedValue} (threshold: ${b.threshold}${b.unit})`).join(", ");
}
resolveIncident = async (incidentId: string, userId: string, teamId: string, comment?: string, userEmail?: string) => {
try {
if (!incidentId) {
throw new AppError({ message: "No incident ID in request", service: SERVICE_NAME, method: "resolveIncident" });
}
if (!userId) {
throw new AppError({ message: "No user ID in request", service: SERVICE_NAME, method: "resolveIncident" });
}
if (!teamId) {
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "resolveIncident" });
}
const incident = await this.incidentsRepository.findActiveByIncidentId(incidentId, teamId);
if (!incident) {
throw new AppError({ message: "Incident not found", service: SERVICE_NAME, method: "resolveIncident" });
}
if (incident.status === false) {
throw new AppError({ message: "Incident is already resolved", service: SERVICE_NAME, method: "resolveIncident" });
}
incident.resolutionType = "manual";
incident.status = false;
incident.resolvedBy = userId;
incident.resolvedByEmail = userEmail || null;
incident.comment = comment || null;
incident.endTime = Date.now().toString();
const resolvedIncident = await this.incidentsRepository.updateById(incident.id, teamId, incident);
this.logger.debug({
service: SERVICE_NAME,
method: "resolveIncidentManually",
message: `Incident manually resolved by user`,
details: { incidentId: resolvedIncident.id },
});
return resolvedIncident;
} catch (error: unknown) {
this.logger.error({
service: SERVICE_NAME,
method: "resolveIncident",
message: error instanceof Error ? error.message : "Unknown error",
details: { id: incidentId },
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
};
getIncidentsByTeam = async (
teamId: string,
sortOrder: string,
dateRange: string,
page: number,
rowsPerPage: number,
status: boolean | undefined,
monitorId: string | undefined,
resolutionType: string | undefined
) => {
try {
if (!teamId) {
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getIncidentsByTeam", status: 400 });
}
const startDate = getDateForRange(dateRange);
const parsedPage = page ?? 0;
const parsedRowsPerPage = rowsPerPage ?? 20;
const incidents = await this.incidentsRepository.findByTeamId(
teamId,
startDate,
parsedPage,
parsedRowsPerPage,
sortOrder,
status,
monitorId,
resolutionType
);
const count = await this.incidentsRepository.countByTeamId(teamId, startDate, status, monitorId, resolutionType);
return { incidents, count };
} catch (error: unknown) {
this.logger.error({
service: SERVICE_NAME,
method: "getIncidentsByTeam",
message: error instanceof Error ? error.message : "Unknown error",
details: { teamId },
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
};
getIncidentSummary = async (teamId: string, limit?: number) => {
try {
if (!teamId) {
throw new AppError({ message: "No team ID in request", service: SERVICE_NAME, method: "getIncidentSummary", status: 400 });
}
const parsedLimit = limit ?? 10;
const summary = await this.incidentsRepository.findSummaryByTeamId(teamId, parsedLimit);
return summary;
} catch (error: unknown) {
this.logger.error({
service: SERVICE_NAME,
method: "getIncidentSummary",
message: error instanceof Error ? error.message : "Unknown error",
details: { teamId },
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
};
getIncidentById = async (incidentId: string, teamId: string) => {
try {
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);
}
return { incident, monitor, user };
} catch (error: unknown) {
this.logger.error({
service: SERVICE_NAME,
method: "getIncidentById",
message: error instanceof Error ? error.message : "Unknown error",
details: { incidentId },
stack: error instanceof Error ? error.stack : undefined,
});
throw error;
}
};
}
@@ -0,0 +1,50 @@
// export type IncidentResolutionType = "automatic" | "manual" | null;
export const IncidentResolutionTypes = ["automatic", "manual", null] as const;
export type IncidentResolutionType = (typeof IncidentResolutionTypes)[number];
export interface Incident {
id: string;
monitorId: string;
teamId: string;
startTime: string;
endTime: string | null;
status: boolean;
message?: string | null;
statusCode?: number | null;
resolutionType: IncidentResolutionType;
resolvedBy?: string | null;
resolvedByEmail?: string | null;
comment?: string | null;
createdAt: string;
updatedAt: string;
}
export interface IncidentSummaryTopMonitor {
monitorId: string;
monitorName: string | null;
incidentCount: number;
}
export interface IncidentSummaryItem {
id: string;
monitorId: string;
monitorName: string | null;
status: boolean;
startTime: string;
endTime: string | null;
resolutionType: IncidentResolutionType;
message: string | null;
statusCode: number | null;
createdAt: string;
}
export interface IncidentSummary {
total: number;
totalActive: number;
totalManualResolutions: number;
totalAutomaticResolutions: number;
avgResolutionTimeHours: number;
topMonitor: IncidentSummaryTopMonitor | null;
latestIncidents: IncidentSummaryItem[];
}