Files
Checkmate/server/src/services/business/MonitorService.ts
T

388 lines
9.5 KiB
TypeScript
Raw Normal View History

2026-01-05 17:58:47 +00:00
import { MonitorStats } from "@/db/models/index.js";
2025-11-13 13:47:26 -08:00
import ApiError from "@/utils/ApiError.js";
import { IJobQueue } from "@/services/infrastructure/JobQueue.js";
import { MonitorWithChecksResponse } from "@/types/index.js";
2026-01-05 17:58:47 +00:00
import { MonitorStatus } from "@/types/domain/index.js";
2025-11-29 19:24:08 +00:00
import { Entitlements } from "@/types/entitlements.js";
2025-12-19 19:10:06 +00:00
import { getStartDate } from "@/utils/TimeUtils.js";
2026-01-05 17:58:47 +00:00
import { IMonitorRepository, IChecksRepository } from "@/repositories/index.js";
import type { Monitor, MonitorType } from "@/types/domain/index.js";
2025-11-20 23:27:30 +00:00
2025-11-30 16:52:48 +00:00
export enum MonitorImportCode {
OK = "OK",
PARTIAL = "PARTIAL",
NO_CAPACITY = "NO_CAPACITY",
UNEXPECTED = "UNEXPECTED",
}
export interface MonitorImportResult {
ok: boolean;
status: number;
code: MonitorImportCode;
attempted: number;
eligible: number;
imported: number;
errors: number;
message?: string;
}
2025-11-13 13:47:26 -08:00
const SERVICE_NAME = "MonitorService";
export interface IMonitorService {
create: (
orgId: string,
userId: string,
currentTeamId: string,
2026-01-04 22:44:39 +00:00
monitorData: Monitor
) => Promise<Monitor>;
getAll: (teamId: string) => Promise<Monitor[]>;
2025-11-13 13:47:26 -08:00
getAllEmbedChecks: (
teamId: string,
2025-11-26 22:22:15 +00:00
search: string,
2025-11-19 20:53:25 +00:00
sortField: string,
sortOrder: string,
2025-11-13 13:47:26 -08:00
page: number,
limit: number,
2025-11-18 21:43:35 +00:00
type: MonitorType[],
status: MonitorStatus[]
2025-11-13 13:47:26 -08:00
) => Promise<{
count: number;
upCount: number;
downCount: number;
pausedCount: number;
monitors: any[];
}>;
2026-01-04 22:44:39 +00:00
get: (teamId: string, monitorId: string) => Promise<Monitor>;
2025-11-13 13:47:26 -08:00
getEmbedChecks: (
teamId: string,
monitorId: string,
2025-12-17 21:11:51 +00:00
range: string
2025-11-13 13:47:26 -08:00
) => Promise<MonitorWithChecksResponse>;
2025-11-19 19:06:17 +00:00
togglePause: (
2025-11-13 13:47:26 -08:00
userId: string,
teamId: string,
monitorId: string
2026-01-04 22:44:39 +00:00
) => Promise<Monitor>;
2025-11-13 13:47:26 -08:00
update: (
userId: string,
teamId: string,
monitorId: string,
2026-01-04 22:44:39 +00:00
updateData: Partial<Monitor>
) => Promise<Monitor>;
2025-11-13 13:47:26 -08:00
delete: (teamId: string, monitorId: string) => Promise<boolean>;
2025-11-26 23:57:40 +00:00
deleteAllInOrg: (orgId: string) => Promise<boolean>;
2025-11-20 23:27:30 +00:00
export: (teamId: string) => Promise<Array<Record<string, unknown>>>;
import: (
orgId: string,
teamId: string,
userId: string,
2025-11-29 19:24:08 +00:00
entitlements: Entitlements,
2026-01-04 22:44:39 +00:00
data: { monitors: Array<Monitor> }
2025-11-30 16:52:48 +00:00
) => Promise<MonitorImportResult>;
2025-11-13 13:47:26 -08:00
}
class MonitorService implements IMonitorService {
public SERVICE_NAME: string;
private jobQueue: IJobQueue;
2026-01-02 22:16:00 +00:00
private monitorRepository: IMonitorRepository;
2026-01-03 21:16:46 +00:00
private checksRepository: IChecksRepository;
constructor(
jobQueue: IJobQueue,
monitorRepository: IMonitorRepository,
checksRepository: IChecksRepository
) {
2025-11-13 13:47:26 -08:00
this.SERVICE_NAME = SERVICE_NAME;
this.jobQueue = jobQueue;
2026-01-02 22:16:00 +00:00
this.monitorRepository = monitorRepository;
2026-01-03 21:16:46 +00:00
this.checksRepository = checksRepository;
2025-11-13 13:47:26 -08:00
}
create = async (
orgId: string,
userId: string,
currentTeamId: string,
2026-01-04 22:44:39 +00:00
monitorData: Monitor
2025-11-13 13:47:26 -08:00
) => {
2026-01-02 23:28:36 +00:00
const monitor = await this.monitorRepository.create(
orgId,
userId,
currentTeamId,
monitorData
);
2025-11-13 13:47:26 -08:00
await MonitorStats.create({
2026-01-02 23:28:36 +00:00
monitorId: monitor.id,
2025-11-13 13:47:26 -08:00
currentStreakStartedAt: Date.now(),
});
await this.jobQueue.addJob(monitor);
return monitor;
};
getAll = async (teamId: string) => {
2026-01-02 22:16:00 +00:00
return await this.monitorRepository.findByTeamId(teamId);
2025-11-13 13:47:26 -08:00
};
getAllEmbedChecks = async (
teamId: string,
2025-11-26 22:22:15 +00:00
search: string,
2025-11-19 20:53:25 +00:00
sortField: string,
sortOrder: string,
2025-11-13 13:47:26 -08:00
page: number,
rowsPerPage: number,
2025-11-18 21:43:35 +00:00
type: MonitorType[] = [],
status: MonitorStatus[] = []
2025-11-13 13:47:26 -08:00
) => {
2026-01-02 22:16:00 +00:00
const counts = await this.monitorRepository.findMonitorCountsByTeamId(
teamId
);
2025-11-18 21:43:35 +00:00
2026-01-02 22:16:00 +00:00
const monitors = await this.monitorRepository.findByTeamIdWithConfig(
teamId,
2025-11-13 13:47:26 -08:00
{
2026-01-02 22:16:00 +00:00
search,
sortField,
sortOrder,
page,
rowsPerPage,
type,
status,
}
);
2025-11-13 13:47:26 -08:00
2026-01-04 22:24:55 +00:00
const checks = await this.checksRepository.findLatestChecksByMonitorIds(
monitors.map((m) => m.id)
2026-01-02 20:33:34 +00:00
);
2025-11-13 13:47:26 -08:00
2026-01-04 22:24:55 +00:00
const checksMap = new Map(checks.map((c: any) => [c.id, c.latestChecks]));
2025-11-13 13:47:26 -08:00
return {
count: counts.total,
upCount: counts.upCount,
downCount: counts.downCount,
pausedCount: counts.pausedCount,
monitors,
2026-01-02 20:33:34 +00:00
checksMap: Object.fromEntries(checksMap),
2025-11-13 13:47:26 -08:00
};
};
get = async (teamId: string, monitorId: string) => {
2026-01-02 22:16:00 +00:00
const monitor = await this.monitorRepository.findById(monitorId, teamId);
2025-11-13 13:47:26 -08:00
if (!monitor) {
throw new ApiError("Monitor not found", 404);
}
return monitor;
};
2025-12-19 18:26:24 +00:00
getEmbedChecks = async (
teamId: string,
monitorId: string,
range: string
): Promise<MonitorWithChecksResponse> => {
2026-01-02 22:16:00 +00:00
const monitor = await this.monitorRepository.findById(monitorId, teamId);
2025-12-19 18:26:24 +00:00
if (!monitor) {
throw new ApiError("Monitor not found", 404);
}
2025-12-29 23:00:39 +00:00
if (!monitor) {
throw new ApiError("Monitor not found", 404);
}
2026-01-05 17:58:47 +00:00
const stats = await MonitorStats.findOne({
monitorId: monitor.id,
});
if (!stats) {
throw new ApiError("Monitor stats not found", 404);
}
2025-12-19 19:10:06 +00:00
const startDate = getStartDate(range);
2025-12-19 18:26:24 +00:00
if (range === "24h" || range === "7d" || range === "30d") {
2026-01-05 17:58:47 +00:00
const checks = await this.checksRepository.findDateRangeChecksByMonitor(
monitor,
startDate,
range
);
return {
checks,
monitor,
stats,
};
2025-12-19 18:26:24 +00:00
} else {
2026-01-05 04:17:11 +00:00
const checks = await this.checksRepository.findRecentChecksByMonitor(
monitor,
startDate
);
return {
checks,
monitor,
stats,
};
2025-12-19 18:26:24 +00:00
}
};
2025-11-19 19:06:17 +00:00
async togglePause(userId: string, teamId: string, id: string) {
2026-01-02 23:28:36 +00:00
const updatedMonitor = await this.monitorRepository.togglePauseById(
id,
teamId,
userId
2025-11-13 13:47:26 -08:00
);
if (!updatedMonitor) {
throw new ApiError("Monitor not found", 404);
}
await this.jobQueue.updateJob(updatedMonitor);
2025-11-19 19:06:17 +00:00
if (updatedMonitor?.status !== "paused") {
2025-11-13 13:47:26 -08:00
await this.jobQueue.resumeJob(updatedMonitor);
} else {
await this.jobQueue.pauseJob(updatedMonitor);
}
return updatedMonitor;
}
async update(
userId: string,
teamId: string,
monitorId: string,
2026-01-04 22:44:39 +00:00
updateData: Partial<Monitor>
2025-11-13 13:47:26 -08:00
) {
2026-01-04 22:44:39 +00:00
const allowedFields: (keyof Monitor)[] = [
2025-11-13 13:47:26 -08:00
"name",
"secret",
"interval",
2025-11-27 20:41:49 +00:00
"rejectUnauthorized",
2025-11-13 13:47:26 -08:00
"n",
"notificationChannels",
2025-12-04 21:52:50 +00:00
"thresholds",
2025-11-13 13:47:26 -08:00
];
2026-01-04 22:44:39 +00:00
const safeUpdate: Partial<Monitor> = {};
2025-11-13 13:47:26 -08:00
for (const field of allowedFields) {
if (updateData[field] !== undefined) {
(safeUpdate as any)[field] = updateData[field];
}
}
2026-01-02 23:28:36 +00:00
const updatedMonitor = await this.monitorRepository.updateById(
monitorId,
teamId,
userId,
safeUpdate
2025-11-13 13:47:26 -08:00
);
if (!updatedMonitor) {
throw new ApiError("Monitor not found", 404);
}
await this.jobQueue.updateJob(updatedMonitor);
return updatedMonitor;
}
async delete(teamId: string, monitorId: string) {
2026-01-02 23:28:36 +00:00
const monitor = await this.monitorRepository.findById(monitorId, teamId);
2025-11-13 13:47:26 -08:00
if (!monitor) {
throw new ApiError("Monitor not found", 404);
}
const deleted = await this.jobQueue.deleteJob(monitor);
if (!deleted) {
throw new ApiError("Failed to delete monitor job from queue", 500);
}
2026-01-02 23:28:36 +00:00
await this.monitorRepository.deleteById(monitorId, teamId);
2025-11-13 13:47:26 -08:00
return true;
}
2025-11-20 23:27:30 +00:00
2025-11-26 23:57:40 +00:00
async deleteAllInOrg(orgId: string) {
2026-01-02 23:28:36 +00:00
const montiors = await this.monitorRepository.findByOrgId(orgId);
2025-11-26 23:57:40 +00:00
for (const monitor of montiors) {
await this.jobQueue.deleteJob(monitor);
}
2026-01-02 23:28:36 +00:00
return await this.monitorRepository.deleteByOrgId(orgId);
2025-11-26 23:57:40 +00:00
}
2025-11-20 23:27:30 +00:00
export = async (teamId: string) => {
2026-01-02 23:28:36 +00:00
const monitor = await this.monitorRepository.findByTeamId(teamId);
return monitor.map((m) => ({
name: m.name,
url: m.url,
port: m.port,
type: m.type,
interval: m.interval,
n: m.n,
secret: m.secret,
}));
2025-11-20 23:27:30 +00:00
};
import = async (
orgId: string,
teamId: string,
userId: string,
2025-11-29 19:24:08 +00:00
entitlements: Entitlements,
2026-01-04 22:44:39 +00:00
data: { monitors: Array<Monitor> }
2025-11-20 23:27:30 +00:00
) => {
2025-11-30 16:52:48 +00:00
const attempted = data.monitors.length ?? 0;
2026-01-04 22:44:39 +00:00
let result: Monitor[] = [];
2025-11-29 19:24:08 +00:00
let canImport = 0;
2025-11-20 23:27:30 +00:00
try {
2025-11-29 19:24:08 +00:00
// Get current count
2026-01-02 23:28:36 +00:00
const monitorCount = await this.monitorRepository.countByOrgId(orgId);
2025-11-29 19:24:08 +00:00
// Check limits, return NO_CAPACITY if at limit
if (monitorCount >= entitlements.monitorsMax) {
return {
ok: true,
status: 200,
attempted,
2025-11-30 16:52:48 +00:00
code: MonitorImportCode.NO_CAPACITY,
2025-11-29 19:24:08 +00:00
eligible: 0,
imported: 0,
errors: attempted,
2025-11-30 16:52:48 +00:00
};
2025-11-29 19:24:08 +00:00
}
// Proceed with import
canImport = entitlements.monitorsMax - monitorCount;
const importableMonitors = data?.monitors.slice(0, canImport);
2026-01-04 22:44:39 +00:00
result = await this.monitorRepository.createMany(
userId,
orgId,
teamId,
importableMonitors
2025-11-20 23:27:30 +00:00
);
for (const monitor of result) {
await this.jobQueue.addJob(monitor);
}
2025-11-29 19:24:08 +00:00
} catch (error: any) {
return {
ok: false,
status: 500,
2025-11-30 16:52:48 +00:00
code: MonitorImportCode.UNEXPECTED,
2025-11-29 19:24:08 +00:00
attempted,
eligible: canImport,
imported: result.length,
errors: Math.max(0, attempted - result.length),
message: error.message,
2025-11-30 16:52:48 +00:00
};
2025-11-20 23:27:30 +00:00
}
2025-11-29 19:24:08 +00:00
const imported = result.length;
const errors = Math.max(0, attempted - imported);
2025-11-30 16:52:48 +00:00
const code =
imported === attempted ? MonitorImportCode.OK : MonitorImportCode.PARTIAL;
2025-11-29 19:24:08 +00:00
const status = imported === attempted ? 200 : 207;
2025-11-20 23:27:30 +00:00
return {
2025-11-29 19:24:08 +00:00
ok: true,
status,
code,
attempted,
eligible: canImport,
imported,
errors,
2025-11-30 16:52:48 +00:00
};
2025-11-20 23:27:30 +00:00
};
2025-11-13 13:47:26 -08:00
}
export default MonitorService;