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

466 lines
15 KiB
TypeScript
Raw Normal View History

2026-01-13 23:59:09 +00:00
import { NormalizeData, NormalizeDataUptimeDetails } from "@/utils/dataUtils.js";
2026-01-13 20:20:00 +00:00
import { type Monitor } from "@/types/index.js";
2026-01-21 09:52:31 -08:00
import type {
MonitorType,
MonitorsWithChecksByTeamIdResult,
UptimeDetailsResult,
HardwareDetailsResult,
PageSpeedDetailsResult,
} from "@/types/monitor.js";
2026-01-15 19:36:41 +00:00
import type { IChecksRepository, IMonitorsRepository, IMonitorStatsRepository, IStatusPagesRepository } from "@/repositories/index.js";
2026-01-13 23:22:34 +00:00
import fs from "fs";
import { fileURLToPath } from "url";
import path from "path";
2026-01-22 21:49:49 +00:00
import { AppError } from "@/utils/AppError.js";
2026-01-21 00:01:38 +00:00
import { ISuperSimpleQueue } from "../infrastructure/SuperSimpleQueue/SuperSimpleQueue.js";
2026-01-13 22:56:51 +00:00
2025-07-24 13:50:21 -07:00
const SERVICE_NAME = "MonitorService";
2026-01-13 23:59:09 +00:00
type DateRangeKey = "recent" | "day" | "week" | "month" | "all";
2026-01-13 20:20:00 +00:00
export interface IMonitorService {
readonly serviceName: string;
// create
createMonitor(teamId: string, userId: string, body: Monitor): Promise<void>;
2026-01-21 09:52:31 -08:00
createBulkMonitors(monitors: Array<Monitor>, userId: string, teamId: string): Promise<Monitor[] | null>;
2026-01-21 00:01:38 +00:00
addDemoMonitors(args: { userId: string; teamId: string }): Promise<Monitor[]>;
2026-01-13 20:20:00 +00:00
// read
2026-01-21 00:01:38 +00:00
getUptimeDetailsById(args: { teamId: string; monitorId: string; dateRange: string; normalize?: boolean }): Promise<UptimeDetailsResult>;
getHardwareDetailsById(args: { teamId: string; monitorId: string; dateRange: string }): Promise<HardwareDetailsResult>;
getPageSpeedDetailsById(args: { teamId: string; monitorId: string; dateRange: string }): Promise<PageSpeedDetailsResult>;
2026-01-14 19:28:17 +00:00
getMonitorById(args: { teamId: string; monitorId: string }): Promise<Monitor>;
2026-01-13 20:20:00 +00:00
getMonitorsByTeamId(args: {
teamId: string;
limit?: number;
2026-01-13 22:56:51 +00:00
type?: MonitorType | MonitorType[];
2026-01-13 20:20:00 +00:00
page?: number;
rowsPerPage?: number;
filter?: string;
field?: string;
order?: "asc" | "desc";
2026-01-21 00:01:38 +00:00
}): Promise<Monitor[] | null>;
2026-01-13 20:20:00 +00:00
getMonitorsWithChecksByTeamId(args: {
teamId: string;
limit?: number;
2026-01-13 22:56:51 +00:00
type?: MonitorType | MonitorType[];
2026-01-13 20:20:00 +00:00
page?: number;
rowsPerPage?: number;
filter?: string;
field?: string;
order?: "asc" | "desc";
explain?: boolean;
2026-01-21 00:01:38 +00:00
}): Promise<MonitorsWithChecksByTeamIdResult>;
2026-01-13 20:20:00 +00:00
getAllGames(): any;
2026-01-15 18:21:36 +00:00
getGroupsByTeamId(args: { teamId: string }): Promise<string[]>;
2026-01-13 20:20:00 +00:00
// update
2026-01-15 18:21:36 +00:00
editMonitor(args: { teamId: string; monitorId: string; body: Monitor }): Promise<Monitor>;
2026-01-15 18:24:58 +00:00
pauseMonitor(args: { teamId: string; monitorId: string }): Promise<Monitor>;
2026-01-13 20:20:00 +00:00
// delete
2026-01-15 18:24:58 +00:00
deleteMonitor(args: { teamId: string; monitorId: string }): Promise<Monitor>;
2026-01-13 20:20:00 +00:00
deleteAllMonitors(args: { teamId: string }): Promise<number>;
// other
sendTestEmail(args: { to: string }): Promise<string>;
2026-01-21 00:01:38 +00:00
exportMonitorsToJSON(args: { teamId: string }): Promise<Monitor[]>;
2026-01-13 20:20:00 +00:00
}
export class MonitorService implements IMonitorService {
2025-07-25 15:15:14 -07:00
static SERVICE_NAME = SERVICE_NAME;
2025-07-24 13:50:21 -07:00
2026-01-21 00:01:38 +00:00
private jobQueue: ISuperSimpleQueue;
2026-01-13 20:20:00 +00:00
private emailService: any;
private logger: any;
private games: any;
private monitorsRepository: IMonitorsRepository;
2026-01-13 23:59:09 +00:00
private checksRepository: IChecksRepository;
2026-01-14 19:28:17 +00:00
private monitorStatsRepository: IMonitorStatsRepository;
2026-01-15 19:36:41 +00:00
private statusPagesRepository: IStatusPagesRepository;
2026-01-13 20:20:00 +00:00
2026-01-12 22:58:46 +00:00
constructor({
jobQueue,
emailService,
logger,
games,
monitorsRepository,
checksRepository,
2026-01-14 19:28:17 +00:00
monitorStatsRepository,
2026-01-15 19:36:41 +00:00
statusPagesRepository,
2026-01-13 20:20:00 +00:00
}: {
2026-01-21 00:01:38 +00:00
jobQueue: ISuperSimpleQueue;
2026-01-13 20:20:00 +00:00
emailService: any;
logger: any;
games: any;
monitorsRepository: IMonitorsRepository;
2026-01-13 23:59:09 +00:00
checksRepository: IChecksRepository;
2026-01-14 19:28:17 +00:00
monitorStatsRepository: IMonitorStatsRepository;
2026-01-15 19:36:41 +00:00
statusPagesRepository: IStatusPagesRepository;
2026-01-12 22:58:46 +00:00
}) {
2025-07-24 13:50:21 -07:00
this.jobQueue = jobQueue;
this.emailService = emailService;
this.logger = logger;
this.games = games;
2026-01-12 22:58:46 +00:00
this.monitorsRepository = monitorsRepository;
this.checksRepository = checksRepository;
2026-01-14 19:28:17 +00:00
this.monitorStatsRepository = monitorStatsRepository;
2026-01-15 19:36:41 +00:00
this.statusPagesRepository = statusPagesRepository;
2025-07-24 13:50:21 -07:00
}
2026-01-13 20:20:00 +00:00
get serviceName(): string {
2025-07-25 15:15:14 -07:00
return MonitorService.SERVICE_NAME;
}
2026-01-13 23:59:09 +00:00
private getDateRange = (dateRange: DateRangeKey) => {
const startDates = {
recent: new Date(new Date().setHours(new Date().getHours() - 2)),
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: new Date(0),
};
return {
start: startDates[dateRange],
end: new Date(),
};
};
private getDateFormat = (dateRange: DateRangeKey): string => {
const formatLookup = {
recent: "%Y-%m-%dT%H:%M:00Z",
day: "%Y-%m-%dT%H:00:00Z",
week: "%Y-%m-%dT00:00:00Z",
month: "%Y-%m-%dT00:00:00Z",
all: "%Y-%m-%dT00:00:00Z",
};
return formatLookup[dateRange];
};
2026-01-13 20:20:00 +00:00
createMonitor = async (teamId: string, userId: string, body: Monitor): Promise<void> => {
const monitor = await this.monitorsRepository.create(body, teamId, userId);
if (!monitor) {
2026-01-22 21:49:49 +00:00
throw new AppError({ message: "Failed to create monitor", status: 500, service: SERVICE_NAME, method: "createMonitor" });
2026-01-13 20:20:00 +00:00
}
2025-07-24 13:50:21 -07:00
2026-01-13 20:20:00 +00:00
this.jobQueue.addJob(monitor.id, monitor);
2025-07-24 13:50:21 -07:00
};
2026-01-21 09:52:31 -08:00
createBulkMonitors = async (monitors: Array<Monitor>, userId: string, teamId: string): Promise<Monitor[] | null> => {
const createdMonitors = await this.monitorsRepository.createBulkMonitors(monitors);
if (!monitors || monitors.length === 0) {
2026-01-22 21:49:49 +00:00
throw new AppError({ message: "Failed to create monitors", status: 500, service: SERVICE_NAME, method: "createBulkMonitors" });
2026-01-21 09:52:31 -08:00
}
await Promise.all(createdMonitors.map((monitor) => this.jobQueue.addJob(monitor.id, monitor)));
return createdMonitors;
2025-07-24 13:50:21 -07:00
};
2026-01-13 20:20:00 +00:00
addDemoMonitors = async ({ userId, teamId }: { userId: string; teamId: string }): Promise<any[]> => {
2026-01-13 23:22:34 +00:00
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const demoMonitorsPath = path.resolve(__dirname, "../../utils/demoMonitors.json");
const demoData = JSON.parse(fs.readFileSync(demoMonitorsPath, "utf8"));
const monitors: Monitor[] = demoData.map((monitor: Monitor) => {
return {
userId,
teamId,
name: monitor.name,
description: monitor.name,
type: "http",
url: monitor.url,
interval: 60000,
};
});
const demoMonitors = await this.monitorsRepository.createBulkMonitors(monitors);
2025-07-24 13:50:21 -07:00
2026-01-13 23:22:34 +00:00
await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor.id, monitor)));
2026-01-13 20:20:00 +00:00
return demoMonitors;
2025-07-24 13:50:21 -07:00
};
2026-01-13 20:20:00 +00:00
getUptimeDetailsById = async ({
teamId,
monitorId,
dateRange,
normalize,
}: {
teamId: string;
monitorId: string;
dateRange: string;
normalize?: boolean;
2026-01-21 00:01:38 +00:00
}): Promise<UptimeDetailsResult> => {
2026-01-13 23:59:09 +00:00
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
if (!monitor) {
throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 });
}
const rangeKey = (dateRange as DateRangeKey) ?? "recent";
const { start, end } = this.getDateRange(rangeKey);
2026-01-20 21:18:26 +00:00
const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), {
2026-01-14 19:28:17 +00:00
type: monitor.type,
2026-01-13 20:20:00 +00:00
});
2026-01-14 19:28:17 +00:00
const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id);
2026-01-14 22:44:23 +00:00
if (
checksData.monitorType !== "http" &&
checksData.monitorType !== "ping" &&
checksData.monitorType !== "docker" &&
checksData.monitorType !== "port" &&
checksData.monitorType !== "game"
) {
2026-01-14 19:28:17 +00:00
throw new AppError({ message: `${monitor.type} monitors are not supported for uptime details`, status: 400 });
}
2026-01-13 20:20:00 +00:00
2026-01-13 23:59:09 +00:00
return {
monitorData: {
monitor,
groupedChecks: NormalizeDataUptimeDetails(checksData.groupedChecks, 10, 100),
groupedUpChecks: NormalizeDataUptimeDetails(checksData.groupedUpChecks, 10, 100),
groupedDownChecks: NormalizeDataUptimeDetails(checksData.groupedDownChecks, 10, 100),
groupedAvgResponseTime: checksData.avgResponseTime,
groupedUptimePercentage: checksData.uptimePercentage,
},
monitorStats,
};
2025-07-24 13:50:21 -07:00
};
2026-01-21 09:52:31 -08:00
getHardwareDetailsById = async ({
teamId,
monitorId,
dateRange,
}: {
teamId: string;
monitorId: string;
dateRange: string;
}): Promise<HardwareDetailsResult> => {
2026-01-14 19:28:17 +00:00
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
if (!monitor) {
throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 });
}
if (monitor.type !== "hardware") {
throw new AppError({ message: `${monitor.type} monitors are not supported for hardware details`, status: 400 });
}
const rangeKey = (dateRange as DateRangeKey) ?? "recent";
const { start, end } = this.getDateRange(rangeKey);
2026-01-20 21:18:26 +00:00
const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), {
2026-01-14 19:28:17 +00:00
type: monitor.type,
2026-01-13 20:20:00 +00:00
});
2026-01-14 19:28:17 +00:00
if (checksData.monitorType !== "hardware") {
throw new AppError({ message: "Unable to load hardware stats for this monitor", status: 500 });
}
2025-07-24 13:50:21 -07:00
2026-01-14 19:28:17 +00:00
const stats = {
aggregateData: checksData.aggregateData,
upChecks: checksData.upChecks,
checks: checksData.checks,
};
2025-07-24 13:50:21 -07:00
2026-01-14 19:28:17 +00:00
return {
...monitor,
stats,
};
2026-01-13 20:20:00 +00:00
};
2025-07-24 13:50:21 -07:00
2026-01-21 09:52:31 -08:00
getPageSpeedDetailsById = async ({
teamId,
monitorId,
dateRange,
}: {
teamId: string;
monitorId: string;
dateRange: string;
}): Promise<PageSpeedDetailsResult> => {
2026-01-14 22:44:23 +00:00
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
if (!monitor) {
throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 });
}
if (monitor.type !== "pagespeed") {
throw new AppError({ message: `${monitor.type} monitors are not supported for pagespeed details`, status: 400 });
}
const rangeKey = (dateRange as DateRangeKey) ?? "recent";
const { start, end } = this.getDateRange(rangeKey);
2026-01-20 21:18:26 +00:00
const checksData = await this.checksRepository.findByDateRangeAndMonitorId(monitor.id, start, end, this.getDateFormat(rangeKey), {
2026-01-14 22:44:23 +00:00
type: monitor.type,
});
if (checksData.monitorType !== "pagespeed") {
throw new AppError({ message: "Unable to load pagespeed stats for this monitor", status: 500 });
}
2026-01-16 21:04:41 +00:00
const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id);
2026-01-14 22:44:23 +00:00
return {
2026-01-16 21:04:41 +00:00
monitor: {
...monitor,
checks: checksData.checks,
},
monitorStats,
2026-01-14 22:44:23 +00:00
};
};
2026-01-21 00:01:38 +00:00
getMonitorById = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise<Monitor> => {
2026-01-14 19:28:17 +00:00
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
2026-01-13 20:20:00 +00:00
return monitor;
2025-07-24 13:50:21 -07:00
};
2026-01-21 09:52:31 -08:00
getMonitorsByTeamId = async ({
teamId,
type,
filter,
}: {
teamId: string;
type?: MonitorType | MonitorType[];
filter?: string;
}): Promise<Monitor[] | null> => {
2026-01-14 21:47:37 +00:00
const monitors = await this.monitorsRepository.findByTeamId(teamId, {
2025-07-24 13:50:21 -07:00
type,
filter,
});
return monitors;
};
2026-01-13 20:20:00 +00:00
getMonitorsWithChecksByTeamId = async ({
teamId,
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
explain,
}: {
teamId: string;
limit?: number;
2026-01-13 22:56:51 +00:00
type?: MonitorType | MonitorType[];
2026-01-13 20:20:00 +00:00
page?: number;
rowsPerPage?: number;
filter?: string;
field?: string;
order?: "asc" | "desc";
explain?: boolean;
2026-01-21 00:01:38 +00:00
}): Promise<MonitorsWithChecksByTeamIdResult> => {
2026-01-26 20:47:29 +00:00
const summary = await this.monitorsRepository.findMonitorsSummaryByTeamId(teamId, { type });
2026-01-12 22:58:46 +00:00
const count = await this.monitorsRepository.findMonitorCountByTeamIdAndType(teamId, { type, filter });
const monitors = await this.monitorsRepository.findByTeamId(teamId, {
2025-07-24 13:50:21 -07:00
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
});
2026-01-12 22:58:46 +00:00
2026-01-14 20:06:37 +00:00
const monitorsList = (monitors ?? []) as Monitor[];
const snapshotTypes: MonitorType[] = ["hardware"];
2026-01-14 20:06:37 +00:00
const requestedTypes = Array.isArray(type) ? type : type ? [type] : [];
const snapshotOnlyRequest =
requestedTypes.length > 0 && requestedTypes.every((requestedType) => snapshotTypes.includes(requestedType as MonitorType));
const monitorsWithChecks = monitorsList.map((monitor: Monitor) => {
2026-01-27 18:26:31 +00:00
const rawChecks = monitor.recentChecks ?? [];
2026-01-14 20:06:37 +00:00
const isSnapshotType = snapshotOnlyRequest || snapshotTypes.includes(monitor.type);
2026-01-27 19:24:02 +00:00
const checks = isSnapshotType ? rawChecks.slice(0, 1) : NormalizeData(rawChecks, 10, 100);
monitor.recentChecks = checks;
return monitor;
2026-01-12 22:58:46 +00:00
});
2026-01-14 23:34:05 +00:00
return { summary: summary ?? null, count, monitors: monitorsWithChecks };
2025-07-24 13:50:21 -07:00
};
2026-01-13 20:20:00 +00:00
getAllGames = (): any => {
return this.games;
};
2026-01-15 18:21:36 +00:00
getGroupsByTeamId = async ({ teamId }: { teamId: string }): Promise<string[]> => {
const groups = await this.monitorsRepository.findGroupsByTeamId(teamId);
2026-01-13 20:20:00 +00:00
return groups;
};
2026-01-15 18:21:36 +00:00
editMonitor = async ({ teamId, monitorId, body }: { teamId: string; monitorId: string; body: Monitor }) => {
2026-01-15 18:33:03 +00:00
const editedMonitor = await this.monitorsRepository.updateById(monitorId, teamId, body);
2026-01-13 20:20:00 +00:00
await this.jobQueue.updateJob(editedMonitor);
2026-01-15 18:21:36 +00:00
return editedMonitor;
2026-01-13 20:20:00 +00:00
};
2026-01-15 18:24:58 +00:00
pauseMonitor = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise<Monitor> => {
2026-01-15 18:21:36 +00:00
const monitor = await this.monitorsRepository.togglePauseById(monitorId, teamId);
monitor.isActive === true ? await this.jobQueue.resumeJob(monitor) : await this.jobQueue.pauseJob(monitor);
2026-01-13 20:20:00 +00:00
return monitor;
};
2026-01-15 18:24:58 +00:00
deleteMonitor = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise<Monitor> => {
const monitor = await this.monitorsRepository.deleteById(monitorId, teamId);
2026-01-26 20:47:29 +00:00
await this.monitorStatsRepository.deleteByMonitorId(monitor.id).catch((err: any) => {
this.logger.warn({
message: `Error deleting monitor stats for monitor ${monitor.id} with name ${monitor.name}`,
service: SERVICE_NAME,
stack: err.stack,
});
});
await this.checksRepository.deleteByMonitorId(monitor.id).catch((err: any) => {
this.logger.warn({
message: `Error deleting checks for monitor ${monitor.id} with name ${monitor.name}`,
service: SERVICE_NAME,
stack: err.stack,
});
});
await this.statusPagesRepository.removeMonitorFromStatusPages(monitor.id).catch((err: any) => {
this.logger.warn({
message: `Error removing monitor ${monitor.id} with name ${monitor.name} from status pages`,
service: SERVICE_NAME,
stack: err.stack,
});
});
2026-01-13 20:20:00 +00:00
await this.jobQueue.deleteJob(monitor);
return monitor;
};
deleteAllMonitors = async ({ teamId }: { teamId: string }): Promise<number> => {
2026-01-13 23:22:34 +00:00
const { monitors, deletedCount } = await this.monitorsRepository.deleteByTeamId(teamId);
2026-01-13 20:20:00 +00:00
await Promise.all(
2026-01-13 23:22:34 +00:00
monitors.map(async (monitor) => {
2026-01-13 20:20:00 +00:00
try {
await this.jobQueue.deleteJob(monitor);
2026-01-15 19:36:41 +00:00
await this.checksRepository.deleteByMonitorId(monitor.id);
await this.statusPagesRepository.removeMonitorFromStatusPages(monitor.id);
await this.monitorStatsRepository.deleteByMonitorId(monitor.id);
2026-01-13 20:20:00 +00:00
} catch (error: any) {
this.logger.warn({
2026-01-13 23:22:34 +00:00
message: `Error deleting associated records for monitor ${monitor.id} with name ${monitor.name}`,
2026-01-13 20:20:00 +00:00
service: SERVICE_NAME,
method: "deleteAllMonitors",
stack: error.stack,
});
}
})
);
return deletedCount;
};
sendTestEmail = async ({ to }: { to: string }): Promise<string> => {
2026-01-20 23:06:23 +00:00
const subject = "Test email from Checkmate";
2026-01-13 20:20:00 +00:00
const context = { testName: "Monitoring System" };
const html = await this.emailService.buildEmail("testEmailTemplate", context);
const messageId = await this.emailService.sendEmail(to, subject, html);
if (!messageId) {
2026-01-22 21:49:49 +00:00
throw new AppError({ message: "Failed to send test email.", service: SERVICE_NAME, method: "sendTestEmail", status: 500 });
2026-01-13 20:20:00 +00:00
}
return messageId;
};
exportMonitorsToJSON = async ({ teamId }: { teamId: string }): Promise<any[]> => {
2026-01-15 18:33:03 +00:00
const monitors = await this.monitorsRepository.findByTeamId(teamId, {});
2025-11-21 10:43:29 -08:00
if (!monitors || monitors.length === 0) {
2026-01-22 21:49:49 +00:00
throw new AppError({ message: "No monitors found to export.", service: SERVICE_NAME, method: "exportMonitorsToJSON", status: 400 });
2025-11-21 10:43:29 -08:00
}
2026-01-15 18:33:03 +00:00
return monitors;
2025-11-21 10:43:29 -08:00
};
2025-07-24 13:50:21 -07:00
}