Files
Checkmate/server/src/domain/monitors/monitor.repository.mongo.ts
T

478 lines
16 KiB
TypeScript

import { MonitorModel } from "@/domain/monitors/monitor.model.js";
import type { MonitorDocument, CheckSnapshotDocument } from "@/domain/monitors/monitor.model.js";
import type { CheckSnapshot } from "@/domain/checks/check.type.js";
import type { Monitor, MonitorScheduleFields, MonitorStatus, MonitorsSummary } from "@/domain/monitors/monitor.type.js";
import mongoose, { type FilterQuery, type PipelineStage } from "mongoose";
import { MongoBulkWriteError } from "mongodb";
import { AppError } from "@/utils/AppError.js";
import { IMonitorsRepository, TeamQueryConfig, SummaryConfig, RecentChecksMode } from "@/domain/monitors/monitor.repository.interface.js";
import { toStringId, toDateString } from "@/utils/mongoMappers.js";
import { toCheckSnapshot } from "@/domain/checks/check.snapshot.js";
class MongoMonitorsRepository implements IMonitorsRepository {
create = async (monitor: Monitor, teamId: string, userId: string) => {
const monitorModel = new MonitorModel({ ...monitor, teamId, userId });
const saved = await monitorModel.save();
return this.toEntity(saved);
};
createMonitors = async (monitors: Monitor[]): Promise<Monitor[]> => {
if (!monitors.length) {
return [];
}
const payload = monitors.map((monitor) => ({ ...monitor, notifications: undefined }));
try {
const inserted = await MonitorModel.insertMany(payload, { ordered: false });
return this.mapDocuments(inserted);
} catch (error: unknown) {
if (error instanceof MongoBulkWriteError && "insertedDocs" in error && Array.isArray(error.insertedDocs) && error.insertedDocs.length > 0) {
return this.mapDocuments(error.insertedDocs);
}
throw error;
}
};
findById = async (monitorId: string, teamId: string): Promise<Monitor> => {
const match: { _id: string; teamId: string } = { _id: monitorId, teamId };
const monitor = await MonitorModel.findOne(match);
if (!monitor) {
throw new AppError({ message: `Monitor with ID ${monitorId} not found`, status: 404 });
}
return this.toEntity(monitor);
};
findByIdLean = async (monitorId: string): Promise<Monitor | null> => {
const monitor = await MonitorModel.findOne({ _id: monitorId }).select({ recentChecks: 0 });
return monitor ? this.toEntity(monitor) : null;
};
findAllForScheduling = async (): Promise<MonitorScheduleFields[]> => {
const docs = await MonitorModel.find({}, { type: 1, isActive: 1, interval: 1, geoCheckEnabled: 1, geoCheckInterval: 1 }).lean();
return docs.map((doc) => ({
id: doc._id.toString(),
type: doc.type,
isActive: doc.isActive,
interval: doc.interval,
geoCheckEnabled: doc.geoCheckEnabled ?? false,
geoCheckInterval: doc.geoCheckInterval ?? 300000,
}));
};
private queryBuilder = (config: TeamQueryConfig, teamId: string): FilterQuery<MonitorDocument> => {
const { filter, field = "createdAt", type, tags } = config ?? {};
const query: FilterQuery<MonitorDocument> = { teamId: new mongoose.Types.ObjectId(teamId) };
if (type !== undefined) {
query.type = Array.isArray(type) ? { $in: type } : type;
}
if (tags !== undefined) {
// Convert to ObjectIds: aggregation $match does no schema casting, so raw strings never match the ObjectId refs
const tagIds = (Array.isArray(tags) ? tags : [tags]).map((tag) => new mongoose.Types.ObjectId(tag));
query.tags = { $in: tagIds };
}
if (filter !== undefined) {
switch (field) {
case "name":
query.$or = [{ name: { $regex: filter, $options: "i" } }, { url: { $regex: filter, $options: "i" } }];
break;
case "isActive":
query.isActive = filter === "true";
break;
case "status":
query.status = filter;
break;
case "type":
query.type = filter;
break;
default:
break;
}
}
return query;
};
private uptimeStatsLookupStages: PipelineStage[] = [
{ $lookup: { from: "monitorstats", localField: "_id", foreignField: "monitorId", as: "stats" } },
{ $addFields: { uptimePercentage: { $arrayElemAt: ["$stats.uptimePercentage", 0] } } },
{ $project: { stats: 0 } },
];
private pageOptions = (config: TeamQueryConfig) => {
const { page = 0, rowsPerPage = 0, field = "createdAt", order = "desc" } = config ?? {};
return { sort: { [field]: order === "asc" ? 1 : -1 } as const, skip: Math.max(page, 0) * rowsPerPage, limit: rowsPerPage };
};
findByTeamId = async (teamId: string, config: TeamQueryConfig, options?: { includeRecentChecks?: boolean }): Promise<Monitor[]> => {
const query = this.queryBuilder(config, teamId);
const { sort, skip, limit } = this.pageOptions(config);
const cursor = MonitorModel.find(query).sort(sort).skip(skip).limit(limit);
if (options?.includeRecentChecks === false) {
cursor.select({ recentChecks: 0 });
}
const documents = await cursor;
return this.mapDocuments(documents);
};
findByTeamIdWithStats = async (teamId: string, config: TeamQueryConfig): Promise<Monitor[]> => {
const { sort, skip, limit } = this.pageOptions(config);
const query = this.queryBuilder(config, teamId);
const pipeline: PipelineStage[] = [
{ $match: query },
{ $sort: sort },
...(limit ? [{ $skip: skip }, { $limit: limit }] : []),
...this.uptimeStatsLookupStages,
];
const documents = await MonitorModel.aggregate(pipeline);
return documents.map((doc) => this.toEntity(doc));
};
private recentChecksStages = (mode: RecentChecksMode = "all"): PipelineStage[] => {
switch (mode) {
case "none":
return [{ $project: { recentChecks: 0 } }];
case "latestHardware":
return [
{
$set: {
recentChecks: {
$cond: [{ $eq: ["$type", "hardware"] }, { $slice: [{ $ifNull: ["$recentChecks", []] }, -1] }, []],
},
},
},
];
case "all":
return [];
}
};
findByIds = async (monitorIds: string[], options?: { recentChecks?: "all" | "latestHardware" | "none" }): Promise<Monitor[]> => {
if (!monitorIds.length) {
return [];
}
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
const pipeline: PipelineStage[] = [
{ $match: { _id: { $in: objectIds } } },
...this.recentChecksStages(options?.recentChecks),
...this.uptimeStatsLookupStages,
];
const documents = await MonitorModel.aggregate(pipeline);
return documents.map((doc) => this.toEntity(doc));
};
findMonitorCountByTeamIdAndType = async (teamId: string, config: TeamQueryConfig): Promise<number> => {
const query = this.queryBuilder(config, teamId);
const count = await MonitorModel.countDocuments(query);
return count;
};
findMonitorCountByProxyId = async (proxyId: string): Promise<number> => {
const count = await MonitorModel.countDocuments({ proxyId });
return count;
};
updateById = async (monitorId: string, teamId: string, patch: Partial<Monitor>, options?: { unsetProxyId?: boolean }) => {
const fields: Partial<Monitor> = { ...patch };
const update: Record<string, unknown> = { $set: fields };
if (options?.unsetProxyId) {
delete fields.proxyId;
update.$unset = { proxyId: "" };
}
const updatedMonitor = await MonitorModel.findOneAndUpdate({ _id: monitorId, teamId }, update, { new: true, runValidators: true });
if (!updatedMonitor) {
throw new AppError({ message: `Failed to update monitor with id ${monitorId}`, status: 500 });
}
return this.toEntity(updatedMonitor);
};
updateByIds = async (monitorIds: string[], teamId: string, updates: Partial<Monitor>, excludeStatuses?: MonitorStatus[]) => {
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
const filter: Record<string, unknown> = { _id: { $in: objectIds }, teamId };
if (excludeStatuses && excludeStatuses.length > 0) {
filter.status = { $nin: excludeStatuses };
}
const updated = await MonitorModel.updateMany(filter, { $set: updates }, { runValidators: true });
return updated.modifiedCount;
};
updateStatusWindowAndChecks = async (
monitorId: string,
teamId: string,
status: boolean,
checkSnapshot: CheckSnapshot,
windowSize: number,
maxRecentChecks: number,
statusPatch?: Partial<Monitor>
): Promise<Monitor> => {
const updatedMonitor = await MonitorModel.findOneAndUpdate(
{ _id: monitorId, teamId },
{
$push: {
statusWindow: { $each: [status], $slice: -windowSize },
recentChecks: { $each: [checkSnapshot], $slice: -maxRecentChecks },
},
...(statusPatch && { $set: statusPatch }),
},
{ returnDocument: "after", projection: { recentChecks: 0 } }
);
if (!updatedMonitor) {
throw new AppError({ message: `Failed to update status and checks for monitor with id ${monitorId}`, status: 500 });
}
return this.toEntity(updatedMonitor);
};
togglePauseById = async (monitorId: string, teamId: string) => {
const monitor = await MonitorModel.findOneAndUpdate(
{ _id: monitorId, teamId },
[
{
$set: {
isActive: { $not: "$isActive" },
status: {
$cond: {
if: { $eq: ["$status", "paused"] },
then: "initializing",
else: "paused",
},
},
},
},
],
{ new: true }
);
if (!monitor) {
throw new AppError({ message: `Monitor with ID ${monitorId} not found for the given team.`, status: 404 });
}
return this.toEntity(monitor);
};
bulkTogglePause = async (monitorIds: string[], teamId: string, pause: boolean): Promise<Monitor[]> => {
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
const filter = {
_id: { $in: objectIds },
teamId: new mongoose.Types.ObjectId(teamId),
isActive: pause, // Only pause if active (true), only resume if inactive (false)
};
const nextStatus = pause ? "paused" : "initializing";
const eligible = await MonitorModel.find(filter);
if (eligible.length === 0) return [];
const now = new Date();
await MonitorModel.updateMany(
{ _id: { $in: eligible.map((doc) => doc._id) } },
{ $set: { isActive: !pause, status: nextStatus, updatedAt: now } },
{ timestamps: false }
);
eligible.forEach((doc) => {
doc.isActive = !pause;
doc.status = nextStatus;
doc.updatedAt = now;
});
return this.mapDocuments(eligible);
};
deleteById = async (monitorId: string, teamId: string) => {
const deletedMonitor = await MonitorModel.findOneAndDelete({ _id: monitorId, teamId });
if (!deletedMonitor) {
throw new AppError({ message: `Monitor with ID ${monitorId} not found for the given team.`, status: 404 });
}
return this.toEntity(deletedMonitor);
};
deleteByTeamId = async (teamId: string) => {
const monitors = await MonitorModel.find({ teamId });
const { deletedCount } = await MonitorModel.deleteMany({ teamId });
return { monitors: this.mapDocuments(monitors), deletedCount };
};
findMonitorsSummaryByTeamId = async (teamId: string, config: SummaryConfig): Promise<MonitorsSummary> => {
const match = this.queryBuilder(config, teamId);
const pipeline = [
{ $match: match },
{
$group: {
_id: null,
totalMonitors: { $sum: 1 },
upMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "up"] }, 1, 0],
},
},
downMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "down"] }, 1, 0],
},
},
pausedMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "paused"] }, 1, 0],
},
},
initializingMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "initializing"] }, 1, 0],
},
},
maintenanceMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "maintenance"] }, 1, 0],
},
},
breachedMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "breached"] }, 1, 0],
},
},
},
},
{ $project: { _id: 0 } },
];
const [summary] = await MonitorModel.aggregate(pipeline);
return (
summary ?? {
totalMonitors: 0,
upMonitors: 0,
downMonitors: 0,
pausedMonitors: 0,
initializingMonitors: 0,
maintenanceMonitors: 0,
breachedMonitors: 0,
}
);
};
removeNotificationFromMonitors = async (notificationId: string): Promise<void> => {
await MonitorModel.updateMany({ notifications: notificationId }, { $pull: { notifications: notificationId } });
};
removeTagFromMonitors = async (tagId: string): Promise<void> => {
await MonitorModel.updateMany({ tags: tagId }, { $pull: { tags: tagId } });
};
updateNotifications = async (
teamId: string,
monitorIds: string[],
notificationIds: string[],
action: "add" | "remove" | "set"
): Promise<number> => {
let objectIds;
let notificationObjectIds;
try {
objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
notificationObjectIds = notificationIds.map((id) => new mongoose.Types.ObjectId(id));
} catch {
throw new AppError({ message: "One or more monitor or notification IDs are invalid", status: 400 });
}
const filter = { _id: { $in: objectIds }, teamId: new mongoose.Types.ObjectId(teamId) };
let update;
switch (action) {
case "add":
update = { $addToSet: { notifications: { $each: notificationObjectIds } } };
break;
case "remove":
update = { $pull: { notifications: { $in: notificationObjectIds } } };
break;
case "set":
update = { $set: { notifications: notificationObjectIds } };
break;
default:
throw new AppError({ message: `Invalid action: ${action}`, status: 400 });
}
const result = await MonitorModel.updateMany(filter, update);
return result.modifiedCount;
};
private mapDocuments = (documents: MonitorDocument[]): Monitor[] => {
if (!documents?.length) {
return [];
}
return documents.map((doc) => this.toEntity(doc));
};
private toEntity = (doc: MonitorDocument): Monitor => {
const notificationIds = (doc.notifications ?? []).map((notification) => toStringId(notification));
const tagIds = (doc.tags ?? []).map((tag) => toStringId(tag));
return {
id: toStringId(doc._id),
userId: toStringId(doc.userId),
teamId: toStringId(doc.teamId),
name: doc.name,
description: doc.description ?? undefined,
method: doc.method ?? "GET",
status: doc.status ?? "initializing",
statusWindow: doc.statusWindow ?? [],
statusWindowSize: doc.statusWindowSize,
statusWindowThreshold: doc.statusWindowThreshold,
type: doc.type,
ignoreTlsErrors: doc.ignoreTlsErrors,
proxyMode: doc.proxyMode ?? "inherit",
proxyId: doc.proxyId ? toStringId(doc.proxyId) : undefined,
useAdvancedMatching: doc.useAdvancedMatching ?? false,
jsonPath: doc.jsonPath ?? undefined,
expectedValue: doc.expectedValue ?? undefined,
matchMethod: doc.matchMethod ?? undefined,
url: doc.url,
port: doc.port ?? undefined,
isActive: doc.isActive,
interval: doc.interval,
uptimePercentage: doc.uptimePercentage ?? undefined,
notifications: notificationIds,
tags: tagIds,
customUpCodes: doc.customUpCodes ?? [],
secret: doc.secret ?? undefined,
sshPrivateKey: doc.sshPrivateKey ?? undefined,
cpuAlertThreshold: doc.cpuAlertThreshold,
cpuAlertCounter: doc.cpuAlertCounter,
memoryAlertThreshold: doc.memoryAlertThreshold,
memoryAlertCounter: doc.memoryAlertCounter,
diskAlertThreshold: doc.diskAlertThreshold,
diskAlertCounter: doc.diskAlertCounter,
tempAlertThreshold: doc.tempAlertThreshold,
tempAlertCounter: doc.tempAlertCounter,
selectedDisks: doc.selectedDisks ?? [],
gameId: doc.gameId ?? undefined,
grpcServiceName: doc.grpcServiceName ?? undefined,
strategy: doc.strategy ?? undefined,
group: doc.group ?? null,
recentChecks: (doc.recentChecks ?? []).map((check: CheckSnapshotDocument) => toCheckSnapshot(check)),
geoCheckEnabled: doc.geoCheckEnabled ?? false,
geoCheckLocations: doc.geoCheckLocations ?? [],
geoCheckInterval: doc.geoCheckInterval ?? 300000,
dnsServer: doc.dnsServer ?? undefined,
dnsRecordType: doc.dnsRecordType ?? undefined,
createdAt: toDateString(doc.createdAt),
updatedAt: toDateString(doc.updatedAt),
lastEvaluatedAt: doc.lastEvaluatedAt,
};
};
deleteByTeamIdsNotIn = async (teamIds: string[]): Promise<number> => {
const objectIds = teamIds.map((id) => new mongoose.Types.ObjectId(id));
const result = await MonitorModel.deleteMany({ teamId: { $nin: objectIds } });
return result.deletedCount ?? 0;
};
findAllMonitorIds = async (): Promise<string[]> => {
const monitors = await MonitorModel.find({}, { _id: 1 }).lean();
return monitors.map((doc) => doc._id.toString());
};
}
export default MongoMonitorsRepository;