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

501 lines
17 KiB
TypeScript
Raw Normal View History

2026-06-09 12:34:15 -07:00
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";
2026-08-04 15:16:03 -07:00
import type { Monitor, MonitorScheduleFields, MonitorStatus, MonitorsSummary } from "@/domain/monitors/monitor.type.js";
2026-01-22 20:57:20 +00:00
import mongoose, { type FilterQuery, type PipelineStage } from "mongoose";
2026-03-20 12:16:23 -07:00
import { MongoBulkWriteError } from "mongodb";
2026-01-13 20:20:00 +00:00
import { AppError } from "@/utils/AppError.js";
2026-08-19 10:20:21 -07:00
import { IMonitorsRepository, TeamQueryConfig, SummaryConfig, RecentChecksMode } from "@/domain/monitors/monitor.repository.interface.js";
2026-07-15 10:20:16 -07:00
import { toStringId, toDateString } from "@/utils/mongoMappers.js";
2026-08-04 11:27:32 -07:00
import { toCheckSnapshot } from "@/domain/checks/check.snapshot.js";
2026-01-12 19:32:23 +00:00
class MongoMonitorsRepository implements IMonitorsRepository {
2026-01-13 20:20:00 +00:00
create = async (monitor: Monitor, teamId: string, userId: string) => {
const monitorModel = new MonitorModel({ ...monitor, teamId, userId });
const saved = await monitorModel.save();
return this.toEntity(saved);
};
2026-02-21 16:17:23 +00:00
createMonitors = async (monitors: Monitor[]): Promise<Monitor[]> => {
2026-01-13 23:22:34 +00:00
if (!monitors.length) {
return [];
}
const payload = monitors.map((monitor) => ({ ...monitor, notifications: undefined }));
2026-02-21 16:17:23 +00:00
try {
const inserted = await MonitorModel.insertMany(payload, { ordered: false });
return this.mapDocuments(inserted);
2026-03-20 12:16:23 -07:00
} catch (error: unknown) {
if (error instanceof MongoBulkWriteError && "insertedDocs" in error && Array.isArray(error.insertedDocs) && error.insertedDocs.length > 0) {
return this.mapDocuments(error.insertedDocs);
2026-02-21 16:17:23 +00:00
}
throw error;
}
2026-01-13 22:56:51 +00:00
};
2026-01-15 20:55:01 +00:00
findById = async (monitorId: string, teamId: string): Promise<Monitor> => {
const match: { _id: string; teamId: string } = { _id: monitorId, teamId };
2026-01-13 23:59:09 +00:00
const monitor = await MonitorModel.findOne(match);
2026-01-13 20:20:00 +00:00
if (!monitor) {
2026-01-15 20:55:01 +00:00
throw new AppError({ message: `Monitor with ID ${monitorId} not found`, status: 404 });
2026-01-13 20:20:00 +00:00
}
return this.toEntity(monitor);
};
2026-06-18 11:06:19 -07:00
findByIdLean = async (monitorId: string): Promise<Monitor | null> => {
2026-08-04 15:16:03 -07:00
const monitor = await MonitorModel.findOne({ _id: monitorId }).select({ recentChecks: 0 });
2026-06-18 11:06:19 -07:00
return monitor ? this.toEntity(monitor) : null;
};
2026-08-04 15:16:03 -07:00
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,
}));
2026-01-12 22:58:46 +00:00
};
2026-07-14 10:46:25 -07:00
private queryBuilder = (config: TeamQueryConfig, teamId: string): FilterQuery<MonitorDocument> => {
const { filter, field = "createdAt", type, tags } = config ?? {};
2026-01-12 22:58:46 +00:00
2026-07-14 10:46:25 -07:00
const query: FilterQuery<MonitorDocument> = { teamId: new mongoose.Types.ObjectId(teamId) };
2026-01-12 22:58:46 +00:00
if (type !== undefined) {
query.type = Array.isArray(type) ? { $in: type } : type;
}
2026-05-19 14:44:18 -07:00
if (tags !== undefined) {
2026-07-14 10:46:25 -07:00
// 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 };
2026-05-19 14:44:18 -07:00
}
2026-01-12 22:58:46 +00:00
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":
2026-02-11 18:58:12 +00:00
query.status = filter;
2026-01-12 22:58:46 +00:00
break;
case "type":
query.type = filter;
break;
default:
break;
}
}
2026-07-14 10:46:25 -07:00
return query;
};
private uptimeStatsLookupStages: PipelineStage[] = [
{ $lookup: { from: "monitorstats", localField: "_id", foreignField: "monitorId", as: "stats" } },
{ $addFields: { uptimePercentage: { $arrayElemAt: ["$stats.uptimePercentage", 0] } } },
{ $project: { stats: 0 } },
];
2026-01-12 22:58:46 +00:00
2026-07-23 09:36:06 -07:00
private pageOptions = (config: TeamQueryConfig) => {
2026-07-14 10:46:25 -07:00
const { page = 0, rowsPerPage = 0, field = "createdAt", order = "desc" } = config ?? {};
2026-09-23 12:21:26 +02:00
const direction: 1 | -1 = order === "asc" ? 1 : -1;
2026-09-23 12:38:57 +02:00
const sort: Record<string, 1 | -1> = { [field]: direction };
if (field !== "createdAt") {
sort.createdAt = 1;
}
2026-09-23 12:21:26 +02:00
return { sort, skip: Math.max(page, 0) * rowsPerPage, limit: rowsPerPage };
2026-07-23 09:36:06 -07:00
};
2026-08-04 15:30:34 -07:00
findByTeamId = async (teamId: string, config: TeamQueryConfig, options?: { includeRecentChecks?: boolean }): Promise<Monitor[]> => {
2026-07-14 10:46:25 -07:00
const query = this.queryBuilder(config, teamId);
2026-07-23 09:36:06 -07:00
const { sort, skip, limit } = this.pageOptions(config);
2026-08-04 15:30:34 -07:00
const cursor = MonitorModel.find(query).sort(sort).skip(skip).limit(limit);
if (options?.includeRecentChecks === false) {
cursor.select({ recentChecks: 0 });
}
const documents = await cursor;
2026-01-12 22:58:46 +00:00
return this.mapDocuments(documents);
};
findByTeamIdWithStats = async (teamId: string, config: TeamQueryConfig): Promise<Monitor[]> => {
2026-07-23 09:36:06 -07:00
const { sort, skip, limit } = this.pageOptions(config);
2026-07-14 10:46:25 -07:00
const query = this.queryBuilder(config, teamId);
2026-06-06 16:08:00 -07:00
const pipeline: PipelineStage[] = [
{ $match: query },
{ $sort: sort },
2026-07-23 09:36:06 -07:00
...(limit ? [{ $skip: skip }, { $limit: limit }] : []),
2026-07-14 10:46:25 -07:00
...this.uptimeStatsLookupStages,
2026-06-06 16:08:00 -07:00
];
const documents = await MonitorModel.aggregate(pipeline);
return documents.map((doc) => this.toEntity(doc));
};
2026-08-19 10:20:21 -07:00
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 [];
}
2026-01-15 20:55:01 +00:00
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
2026-08-04 15:30:34 -07:00
const pipeline: PipelineStage[] = [
{ $match: { _id: { $in: objectIds } } },
2026-08-19 10:20:21 -07:00
...this.recentChecksStages(options?.recentChecks),
2026-08-04 15:30:34 -07:00
...this.uptimeStatsLookupStages,
];
const documents = await MonitorModel.aggregate(pipeline);
return documents.map((doc) => this.toEntity(doc));
2026-01-15 20:55:01 +00:00
};
2026-07-14 10:46:25 -07:00
findMonitorCountByTeamIdAndType = async (teamId: string, config: TeamQueryConfig): Promise<number> => {
const query = this.queryBuilder(config, teamId);
2026-01-12 22:58:46 +00:00
const count = await MonitorModel.countDocuments(query);
return count;
};
2026-08-20 11:31:51 -07:00
findMonitorCountByProxyId = async (proxyId: string): Promise<number> => {
const count = await MonitorModel.countDocuments({ proxyId });
return count;
};
2026-08-26 11:19:08 -07:00
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 });
2026-01-13 20:20:00 +00:00
if (!updatedMonitor) {
throw new AppError({ message: `Failed to update monitor with id ${monitorId}`, status: 500 });
}
return this.toEntity(updatedMonitor);
};
2026-05-21 11:02:59 -07:00
updateByIds = async (monitorIds: string[], teamId: string, updates: Partial<Monitor>, excludeStatuses?: MonitorStatus[]) => {
2026-05-21 09:59:23 -07:00
const objectIds = monitorIds.map((id) => new mongoose.Types.ObjectId(id));
2026-05-21 11:02:59 -07:00
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 });
2026-05-21 09:59:23 -07:00
return updated.modifiedCount;
};
2026-04-16 10:41:00 -07:00
updateStatusWindowAndChecks = async (
monitorId: string,
teamId: string,
status: boolean,
checkSnapshot: CheckSnapshot,
windowSize: number,
maxRecentChecks: number,
statusPatch?: Partial<Monitor>
2026-04-16 10:41:00 -07:00
): Promise<Monitor> => {
const updatedMonitor = await MonitorModel.findOneAndUpdate(
{ _id: monitorId, teamId },
{
$push: {
statusWindow: { $each: [status], $slice: -windowSize },
recentChecks: { $each: [checkSnapshot], $slice: -maxRecentChecks },
},
...(statusPatch && { $set: statusPatch }),
2026-04-16 10:41:00 -07:00
},
2026-08-04 15:16:03 -07:00
{ returnDocument: "after", projection: { recentChecks: 0 } }
2026-04-16 10:41:00 -07:00
);
if (!updatedMonitor) {
throw new AppError({ message: `Failed to update status and checks for monitor with id ${monitorId}`, status: 500 });
}
return this.toEntity(updatedMonitor);
};
2026-01-15 18:21:36 +00:00
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",
},
},
2026-01-15 18:21:36 +00:00
},
},
],
{ 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);
};
2026-01-15 18:24:58 +00:00
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);
};
2026-01-13 23:22:34 +00:00
deleteByTeamId = async (teamId: string) => {
const monitors = await MonitorModel.find({ teamId });
const { deletedCount } = await MonitorModel.deleteMany({ teamId });
return { monitors: this.mapDocuments(monitors), deletedCount };
};
findDockerTlsKeyById = async (monitorId: string): Promise<string | null> => {
const doc = await MonitorModel.findOne({ _id: monitorId }, { dockerTlsKey: 1 }).lean();
return doc?.dockerTlsKey ?? null;
};
findAllDockerTlsKeys = async (): Promise<{ id: string; dockerTlsKey: string }[]> => {
const docs = await MonitorModel.find({ dockerTlsKeySet: true }, { dockerTlsKey: 1 }).lean();
return docs.flatMap((doc) => (doc.dockerTlsKey ? [{ id: doc._id.toString(), dockerTlsKey: doc.dockerTlsKey }] : []));
};
updateDockerTlsKey = async (monitorId: string, dockerTlsKey: string): Promise<void> => {
await MonitorModel.updateOne({ _id: monitorId }, { $set: { dockerTlsKey } });
};
2026-07-14 10:46:25 -07:00
findMonitorsSummaryByTeamId = async (teamId: string, config: SummaryConfig): Promise<MonitorsSummary> => {
const match = this.queryBuilder(config, teamId);
2026-01-14 23:34:05 +00:00
const pipeline = [
{ $match: match },
{
$group: {
_id: null,
totalMonitors: { $sum: 1 },
upMonitors: {
$sum: {
2026-02-11 18:58:12 +00:00
$cond: [{ $eq: ["$status", "up"] }, 1, 0],
2026-01-14 23:34:05 +00:00
},
},
downMonitors: {
$sum: {
2026-02-11 18:58:12 +00:00
$cond: [{ $eq: ["$status", "down"] }, 1, 0],
2026-01-14 23:34:05 +00:00
},
},
pausedMonitors: {
$sum: {
2026-02-11 18:58:12 +00:00
$cond: [{ $eq: ["$status", "paused"] }, 1, 0],
},
},
initializingMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "initializing"] }, 1, 0],
},
},
maintenanceMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "maintenance"] }, 1, 0],
2026-01-14 23:34:05 +00:00
},
},
2026-02-14 22:57:27 +00:00
breachedMonitors: {
$sum: {
$cond: [{ $eq: ["$status", "breached"] }, 1, 0],
},
},
2026-01-14 23:34:05 +00:00
},
},
{ $project: { _id: 0 } },
];
const [summary] = await MonitorModel.aggregate(pipeline);
2026-02-14 22:57:27 +00:00
return (
summary ?? {
totalMonitors: 0,
upMonitors: 0,
downMonitors: 0,
pausedMonitors: 0,
initializingMonitors: 0,
maintenanceMonitors: 0,
breachedMonitors: 0,
}
);
2026-01-14 23:34:05 +00:00
};
2026-01-21 13:51:04 -08:00
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,
2026-03-03 23:28:11 +05:30
monitorIds: string[],
notificationIds: string[],
action: "add" | "remove" | "set"
2026-03-03 23:28:11 +05:30
): 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 });
}
2026-03-03 23:28:11 +05:30
const filter = { _id: { $in: objectIds }, teamId: new mongoose.Types.ObjectId(teamId) };
let update;
switch (action) {
case "add":
update = { $addToSet: { notifications: { $each: notificationObjectIds } } };
2026-03-03 23:28:11 +05:30
break;
case "remove":
update = { $pull: { notifications: { $in: notificationObjectIds } } };
2026-03-03 23:28:11 +05:30
break;
case "set":
update = { $set: { notifications: notificationObjectIds } };
2026-03-03 23:28:11 +05:30
break;
default:
throw new AppError({ message: `Invalid action: ${action}`, status: 400 });
2026-03-03 23:28:11 +05:30
}
const result = await MonitorModel.updateMany(filter, update);
return result.modifiedCount;
};
2026-01-13 20:20:00 +00:00
private mapDocuments = (documents: MonitorDocument[]): Monitor[] => {
2026-01-12 22:58:46 +00:00
if (!documents?.length) {
2026-01-13 20:20:00 +00:00
return [];
2026-01-12 22:58:46 +00:00
}
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));
2026-01-12 22:58:46 +00:00
return {
id: toStringId(doc._id),
userId: toStringId(doc.userId),
teamId: toStringId(doc.teamId),
name: doc.name,
2026-01-22 20:57:20 +00:00
description: doc.description ?? undefined,
2026-06-22 11:24:03 -07:00
method: doc.method ?? "GET",
2026-02-11 18:58:12 +00:00
status: doc.status ?? "initializing",
2026-01-22 20:57:20 +00:00
statusWindow: doc.statusWindow ?? [],
statusWindowSize: doc.statusWindowSize,
statusWindowThreshold: doc.statusWindowThreshold,
type: doc.type,
ignoreTlsErrors: doc.ignoreTlsErrors,
2026-08-20 10:59:40 -07:00
proxyMode: doc.proxyMode ?? "inherit",
proxyId: doc.proxyId ? toStringId(doc.proxyId) : undefined,
2026-01-30 20:21:31 +00:00
useAdvancedMatching: doc.useAdvancedMatching ?? false,
2026-01-22 20:57:20 +00:00
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 ?? [],
2026-01-22 20:57:20 +00:00
secret: doc.secret ?? undefined,
cpuAlertThreshold: doc.cpuAlertThreshold,
2026-02-14 21:49:32 +00:00
cpuAlertCounter: doc.cpuAlertCounter,
2026-01-22 20:57:20 +00:00
memoryAlertThreshold: doc.memoryAlertThreshold,
2026-02-14 21:49:32 +00:00
memoryAlertCounter: doc.memoryAlertCounter,
2026-01-22 20:57:20 +00:00
diskAlertThreshold: doc.diskAlertThreshold,
2026-02-14 21:49:32 +00:00
diskAlertCounter: doc.diskAlertCounter,
2026-01-22 20:57:20 +00:00
tempAlertThreshold: doc.tempAlertThreshold,
2026-02-14 21:49:32 +00:00
tempAlertCounter: doc.tempAlertCounter,
2026-01-22 20:57:20 +00:00
selectedDisks: doc.selectedDisks ?? [],
gameId: doc.gameId ?? undefined,
2026-02-23 10:19:42 +05:30
grpcServiceName: doc.grpcServiceName ?? undefined,
strategy: doc.strategy ?? undefined,
2026-01-22 20:57:20 +00:00
group: doc.group ?? null,
2026-08-04 11:27:32 -07:00
recentChecks: (doc.recentChecks ?? []).map((check: CheckSnapshotDocument) => toCheckSnapshot(check)),
2026-02-24 17:18:22 +00:00
geoCheckEnabled: doc.geoCheckEnabled ?? false,
geoCheckLocations: doc.geoCheckLocations ?? [],
geoCheckInterval: doc.geoCheckInterval ?? 300000,
2026-09-04 14:06:46 -07:00
dockerLogsEnabled: doc.dockerLogsEnabled ?? false,
dockerAlertOnStopped: doc.dockerAlertOnStopped ?? false,
dockerAlertOnUnhealthy: doc.dockerAlertOnUnhealthy ?? false,
2026-09-10 12:26:12 -07:00
dockerTlsCa: doc.dockerTlsCa ?? undefined,
dockerTlsCert: doc.dockerTlsCert ?? undefined,
dockerTlsKeySet: doc.dockerTlsKeySet ?? false,
dnsServer: doc.dnsServer ?? undefined,
dnsRecordType: doc.dnsRecordType ?? undefined,
2026-01-22 20:57:20 +00:00
createdAt: toDateString(doc.createdAt),
updatedAt: toDateString(doc.updatedAt),
2026-06-11 14:18:32 -07:00
lastEvaluatedAt: doc.lastEvaluatedAt,
2026-01-22 20:57:20 +00:00
};
};
2026-01-27 18:50:08 +00:00
2026-02-17 19:03:17 +00:00
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());
};
2026-01-12 19:32:23 +00:00
}
2026-01-12 22:58:46 +00:00
export default MongoMonitorsRepository;