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

567 lines
18 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,
2026-01-30 21:26:27 +00:00
GamesMap,
2026-03-20 09:47:02 -07:00
GroupedGeoCheckResult,
2026-01-21 09:52:31 -08:00
} from "@/types/monitor.js";
2026-03-06 10:46:00 -08:00
import { supportsGeoCheck } from "@/types/monitor.js";
2026-02-24 22:30:28 +00:00
import type { GeoContinent } from "@/types/geoCheck.js";
2026-02-17 18:30:22 +00:00
import type {
IChecksRepository,
2026-02-24 19:19:32 +00:00
IGeoChecksRepository,
2026-02-17 18:30:22 +00:00
IIncidentsRepository,
IMonitorsRepository,
IMonitorStatsRepository,
IStatusPagesRepository,
} from "@/repositories/index.js";
2026-03-06 14:27:57 -08:00
import demoMonitorsData from "@/utils/demoMonitors.json" with { type: "json" };
2026-01-22 21:49:49 +00:00
import { AppError } from "@/utils/AppError.js";
2026-03-20 10:37:29 -07:00
import type { ImportedMonitor } from "@/validation/monitorValidation.js";
2026-01-21 00:01:38 +00:00
import { ISuperSimpleQueue } from "../infrastructure/SuperSimpleQueue/SuperSimpleQueue.js";
2026-03-20 09:58:49 -07:00
import { ILogger } from "@/utils/logger.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
2026-03-11 12:41:27 -07:00
createMonitor(teamId: string, userId: string, body: Partial<Monitor>): Promise<void>;
2026-03-20 09:58:49 -07:00
createMonitors(monitors: Array<Monitor>): 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-03-20 10:37:29 -07:00
getUptimeDetailsById(args: { teamId: string; monitorId: string; dateRange: string }): Promise<UptimeDetailsResult>;
2026-01-21 00:01:38 +00:00
getHardwareDetailsById(args: { teamId: string; monitorId: string; dateRange: string }): Promise<HardwareDetailsResult>;
getPageSpeedDetailsById(args: { teamId: string; monitorId: string; dateRange: string }): Promise<PageSpeedDetailsResult>;
2026-03-20 09:47:02 -07:00
getGeoChecksByMonitorId(args: {
teamId: string;
monitorId: string;
dateRange: string;
continents?: GeoContinent[];
}): Promise<GroupedGeoCheckResult>;
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";
2026-01-21 00:01:38 +00:00
}): Promise<MonitorsWithChecksByTeamIdResult>;
2026-01-30 21:26:27 +00:00
getAllGames(): GamesMap;
2026-01-15 18:21:36 +00:00
getGroupsByTeamId(args: { teamId: string }): Promise<string[]>;
2026-01-13 20:20:00 +00:00
// update
2026-03-11 12:41:27 -07:00
editMonitor(args: { teamId: string; monitorId: string; body: Partial<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>;
// notifications
updateNotifications(args: { teamId: string; monitorIds: string[]; notificationIds: string[]; action: "add" | "remove" | "set" }): Promise<number>;
2026-01-13 20:20:00 +00:00
// other
2026-01-21 00:01:38 +00:00
exportMonitorsToJSON(args: { teamId: string }): Promise<Monitor[]>;
2026-03-20 10:37:29 -07:00
importMonitorsFromJSON(args: { teamId: string; userId: string; monitors: ImportedMonitor[] }): Promise<{ imported: number; errors: string[] }>;
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-03-20 09:58:49 -07:00
private logger: ILogger;
private games: GamesMap;
2026-01-13 20:20:00 +00:00
private monitorsRepository: IMonitorsRepository;
2026-01-13 23:59:09 +00:00
private checksRepository: IChecksRepository;
2026-02-24 19:19:32 +00:00
private geoChecksRepository: IGeoChecksRepository;
2026-01-14 19:28:17 +00:00
private monitorStatsRepository: IMonitorStatsRepository;
2026-01-15 19:36:41 +00:00
private statusPagesRepository: IStatusPagesRepository;
2026-02-17 18:30:22 +00:00
private incidentsRepository: IIncidentsRepository;
2026-01-13 20:20:00 +00:00
2026-01-12 22:58:46 +00:00
constructor({
jobQueue,
logger,
games,
monitorsRepository,
checksRepository,
2026-02-24 19:19:32 +00:00
geoChecksRepository,
2026-01-14 19:28:17 +00:00
monitorStatsRepository,
2026-01-15 19:36:41 +00:00
statusPagesRepository,
2026-02-17 18:30:22 +00:00
incidentsRepository,
2026-01-13 20:20:00 +00:00
}: {
2026-01-21 00:01:38 +00:00
jobQueue: ISuperSimpleQueue;
2026-03-20 09:58:49 -07:00
logger: ILogger;
games: GamesMap;
2026-01-13 20:20:00 +00:00
monitorsRepository: IMonitorsRepository;
2026-01-13 23:59:09 +00:00
checksRepository: IChecksRepository;
2026-02-24 19:19:32 +00:00
geoChecksRepository: IGeoChecksRepository;
2026-01-14 19:28:17 +00:00
monitorStatsRepository: IMonitorStatsRepository;
2026-01-15 19:36:41 +00:00
statusPagesRepository: IStatusPagesRepository;
2026-02-17 18:30:22 +00:00
incidentsRepository: IIncidentsRepository;
2026-01-12 22:58:46 +00:00
}) {
2025-07-24 13:50:21 -07:00
this.jobQueue = jobQueue;
this.logger = logger;
this.games = games;
2026-01-12 22:58:46 +00:00
this.monitorsRepository = monitorsRepository;
this.checksRepository = checksRepository;
2026-02-24 19:19:32 +00:00
this.geoChecksRepository = geoChecksRepository;
2026-01-14 19:28:17 +00:00
this.monitorStatsRepository = monitorStatsRepository;
2026-01-15 19:36:41 +00:00
this.statusPagesRepository = statusPagesRepository;
2026-02-17 18:30:22 +00:00
this.incidentsRepository = incidentsRepository;
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-03-20 09:58:49 -07:00
createMonitors = async (monitors: Array<Monitor>): Promise<Monitor[] | null> => {
2026-02-21 16:17:23 +00:00
const createdMonitors = await this.monitorsRepository.createMonitors(monitors);
2026-04-10 11:15:28 -07:00
if (!createdMonitors || createdMonitors.length === 0) {
2026-02-21 16:17:23 +00:00
throw new AppError({ message: "Failed to create monitors", status: 500, service: SERVICE_NAME, method: "createMonitors" });
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-03-20 09:58:49 -07:00
addDemoMonitors = async ({ userId, teamId }: { userId: string; teamId: string }): Promise<Monitor[]> => {
2026-04-10 11:13:12 -07:00
const monitors = demoMonitorsData.map((monitor) => ({
2026-03-06 14:27:57 -08:00
userId,
teamId,
name: monitor.name,
description: monitor.name,
type: "http" as const,
url: monitor.url,
interval: 60000,
}));
const demoMonitors = await this.monitorsRepository.createMonitors(monitors as unknown as Monitor[]);
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,
}: {
teamId: string;
monitorId: string;
dateRange: string;
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 });
}
2026-04-10 11:13:12 -07:00
const rangeKey = dateRange as DateRangeKey;
2026-01-13 23:59:09 +00:00
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" &&
2026-02-19 13:16:12 +05:30
checksData.monitorType !== "game" &&
2026-03-07 01:11:20 +05:30
checksData.monitorType !== "grpc" &&
checksData.monitorType !== "websocket"
2026-01-14 22:44:23 +00:00
) {
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 });
}
2026-04-10 11:13:12 -07:00
const rangeKey = dateRange as DateRangeKey;
2026-01-14 19:28:17 +00:00
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-04-10 12:33:08 -07:00
if (checksData.monitorType !== "hardware") {
throw new AppError({ message: "Unable to load hardware stats for this monitor", status: 500 });
}
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-28 22:00:33 +00:00
const monitorStats = await this.monitorStatsRepository.findByMonitorId(monitor.id);
2026-01-14 19:28:17 +00:00
return {
2026-01-28 22:00:33 +00:00
monitor,
2026-01-14 19:28:17 +00:00
stats,
2026-01-28 22:00:33 +00:00
monitorStats,
2026-01-14 19:28:17 +00:00
};
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 });
}
2026-04-10 11:13:12 -07:00
const rangeKey = dateRange as DateRangeKey;
2026-01-14 22:44:23 +00:00
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,
});
2026-04-10 12:33:08 -07:00
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-02-21 20:52:47 +00:00
monitorData: {
monitor,
groupedChecks: checksData.groupedChecks,
2026-01-16 21:04:41 +00:00
},
monitorStats,
2026-01-14 22:44:23 +00:00
};
};
2026-02-24 19:19:32 +00:00
2026-02-24 22:30:28 +00:00
getGeoChecksByMonitorId = async ({
teamId,
monitorId,
dateRange,
2026-02-25 18:43:12 +00:00
continents,
2026-02-24 22:30:28 +00:00
}: {
teamId: string;
monitorId: string;
dateRange: string;
2026-02-25 18:43:12 +00:00
continents?: GeoContinent[];
2026-03-20 09:47:02 -07:00
}): Promise<GroupedGeoCheckResult> => {
2026-02-24 19:19:32 +00:00
const monitor = await this.monitorsRepository.findById(monitorId, teamId);
if (!monitor) {
throw new AppError({ message: `Monitor with ID ${monitorId} not found.`, status: 404 });
}
2026-03-06 10:46:00 -08:00
if (!supportsGeoCheck(monitor.type) || !monitor.geoCheckEnabled) {
2026-02-24 19:19:32 +00:00
return { groupedGeoChecks: [] };
}
2026-04-10 11:13:12 -07:00
const rangeKey = dateRange as DateRangeKey;
2026-02-24 19:19:32 +00:00
const { start, end } = this.getDateRange(rangeKey);
2026-02-24 22:30:28 +00:00
const groupedGeoChecks = await this.geoChecksRepository.findGroupedByMonitorIdAndDateRange(
monitor.id,
start,
end,
this.getDateFormat(rangeKey),
2026-02-25 18:43:12 +00:00
continents
2026-02-24 22:30:28 +00:00
);
2026-02-24 19:19:32 +00:00
return { groupedGeoChecks };
};
2026-01-21 00:01:38 +00:00
getMonitorById = async ({ teamId, monitorId }: { teamId: string; monitorId: string }): Promise<Monitor> => {
2026-04-10 11:13:12 -07:00
return await this.monitorsRepository.findById(monitorId, teamId);
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-04-10 11:13:12 -07:00
return await this.monitorsRepository.findByTeamId(teamId, { type, filter });
2025-07-24 13:50:21 -07:00
};
2026-01-13 20:20:00 +00:00
getMonitorsWithChecksByTeamId = async ({
teamId,
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
}: {
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<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-30 21:26:27 +00:00
getAllGames = (): GamesMap => {
2026-01-13 20:20:00 +00:00
return this.games;
};
2026-01-15 18:21:36 +00:00
getGroupsByTeamId = async ({ teamId }: { teamId: string }): Promise<string[]> => {
2026-04-10 11:13:12 -07:00
return await this.monitorsRepository.findGroupsByTeamId(teamId);
2026-01-13 20:20:00 +00:00
};
2026-03-11 12:41:27 -07:00
editMonitor = async ({ teamId, monitorId, body }: { teamId: string; monitorId: string; body: Partial<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-03-13 21:40:28 +05:30
updateNotifications = async ({
teamId,
monitorIds,
notificationIds,
action,
}: {
teamId: string;
monitorIds: string[];
notificationIds: string[];
action: "add" | "remove" | "set";
}): Promise<number> => {
const modifiedCount = await this.monitorsRepository.updateNotifications(teamId, monitorIds, notificationIds, action);
2026-03-13 21:40:28 +05:30
// If notifications were updated, we should update the jobs in the queue
if (modifiedCount > 0) {
const monitors = await this.monitorsRepository.findByIds(monitorIds);
2026-03-13 21:40:28 +05:30
await Promise.all(monitors.map((monitor) => this.jobQueue.updateJob(monitor)));
}
2026-03-13 21:40:28 +05:30
return modifiedCount;
};
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);
2026-03-20 09:58:49 -07:00
if (monitor.isActive) {
await this.jobQueue.resumeJob(monitor);
} else {
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-03-20 09:58:49 -07:00
await this.monitorStatsRepository.deleteByMonitorId(monitor.id).catch((err: unknown) => {
2026-01-26 20:47:29 +00:00
this.logger.warn({
message: `Error deleting monitor stats for monitor ${monitor.id} with name ${monitor.name}`,
service: SERVICE_NAME,
2026-03-20 09:58:49 -07:00
stack: err instanceof Error ? err.stack : undefined,
2026-01-26 20:47:29 +00:00
});
});
2026-03-20 09:58:49 -07:00
await this.checksRepository.deleteByMonitorId(monitor.id).catch((err: unknown) => {
2026-01-26 20:47:29 +00:00
this.logger.warn({
message: `Error deleting checks for monitor ${monitor.id} with name ${monitor.name}`,
service: SERVICE_NAME,
2026-03-20 09:58:49 -07:00
stack: err instanceof Error ? err.stack : undefined,
2026-01-26 20:47:29 +00:00
});
});
2026-03-20 09:58:49 -07:00
await this.statusPagesRepository.removeMonitorFromStatusPages(monitor.id).catch((err: unknown) => {
2026-01-26 20:47:29 +00:00
this.logger.warn({
message: `Error removing monitor ${monitor.id} with name ${monitor.name} from status pages`,
service: SERVICE_NAME,
2026-03-20 09:58:49 -07:00
stack: err instanceof Error ? err.stack : undefined,
2026-01-26 20:47:29 +00:00
});
});
2026-02-17 18:30:22 +00:00
2026-03-20 09:58:49 -07:00
await this.incidentsRepository.deleteByMonitorId(monitor.id, teamId).catch((err: unknown) => {
2026-02-17 18:30:22 +00:00
this.logger.warn({
message: `Error deleting incidents for monitor ${monitor.id} with name ${monitor.name}`,
service: SERVICE_NAME,
2026-03-20 09:58:49 -07:00
stack: err instanceof Error ? err.stack : undefined,
2026-02-17 18:30:22 +00:00
});
});
2026-03-20 09:58:49 -07:00
await this.geoChecksRepository.deleteByMonitorId(monitor.id).catch((err: unknown) => {
2026-02-24 23:20:36 +00:00
this.logger.warn({
message: `Error deleting geo checks for monitor ${monitor.id} with name ${monitor.name}`,
service: SERVICE_NAME,
2026-03-20 09:58:49 -07:00
stack: err instanceof Error ? err.stack : undefined,
2026-02-24 23:20:36 +00:00
});
});
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);
2026-02-24 23:20:36 +00:00
await this.geoChecksRepository.deleteByMonitorId(monitor.id);
2026-01-15 19:36:41 +00:00
await this.statusPagesRepository.removeMonitorFromStatusPages(monitor.id);
await this.monitorStatsRepository.deleteByMonitorId(monitor.id);
2026-03-20 09:58:49 -07:00
} catch (error: unknown) {
2026-01-13 20:20:00 +00:00
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",
2026-03-20 09:58:49 -07:00
stack: error instanceof Error ? error.stack : undefined,
2026-01-13 20:20:00 +00:00
});
}
})
);
return deletedCount;
};
2026-03-20 09:58:49 -07:00
exportMonitorsToJSON = async ({ teamId }: { teamId: string }): Promise<Monitor[]> => {
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
};
2026-02-21 03:43:11 +00:00
importMonitorsFromJSON = async ({
teamId,
userId,
monitors,
}: {
teamId: string;
userId: string;
2026-03-20 10:37:29 -07:00
monitors: ImportedMonitor[];
2026-02-21 03:43:11 +00:00
}): Promise<{ imported: number; errors: string[] }> => {
const errors: string[] = [];
2026-03-20 10:37:29 -07:00
const cleanedMonitors: Monitor[] = monitors.map((monitor) => ({
...monitor,
id: "",
teamId,
userId,
recentChecks: [],
createdAt: "",
updatedAt: "",
}));
2026-02-21 03:43:11 +00:00
2026-03-20 10:37:29 -07:00
const createdMonitors = await this.createMonitors(cleanedMonitors);
2026-02-21 03:43:11 +00:00
2026-04-10 11:15:28 -07:00
return { imported: createdMonitors!.length, errors };
2026-02-21 03:43:11 +00:00
};
2025-07-24 13:50:21 -07:00
}