-> timeseries

This commit is contained in:
Alex Holliday committed 2026-01-12 19:32:23 +00:00
1 parent 5c14c68899
commit e090d3cfd3
91 files changed
+941 -987

No files matched your search

+149
View File
@@ -0,0 +1,149 @@
const SERVICE_NAME = "checkService";
class CheckService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, settingsService, stringService, errorService }) {
this.db = db;
this.settingsService = settingsService;
this.stringService = stringService;
this.errorService = errorService;
}
get serviceName() {
return CheckService.SERVICE_NAME;
}
getChecksByMonitor = async ({ monitorId, query, teamId }) => {
if (!monitorId) {
throw this.errorService.createBadRequestError("No monitor ID in request");
}
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor) {
throw this.errorService.createNotFoundError("Monitor not found");
}
if (!monitor.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
let { sortOrder, dateRange, filter, ack, page, rowsPerPage, status } = query;
const result = await this.db.checkModule.getChecksByMonitor({
monitorId,
sortOrder,
dateRange,
filter,
ack,
page,
rowsPerPage,
status,
});
return result;
};
getChecksByTeam = async ({ teamId, query }) => {
let { sortOrder, dateRange, filter, ack, page, rowsPerPage } = query;
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const checkData = await this.db.checkModule.getChecksByTeam({
sortOrder,
dateRange,
filter,
ack,
page,
rowsPerPage,
teamId,
});
return checkData;
};
getChecksSummaryByTeamId = async ({ teamId }) => {
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const summary = await this.db.checkModule.getChecksSummaryByTeamId({ teamId });
return summary;
};
ackCheck = async ({ checkId, teamId, ack }) => {
if (!checkId) {
throw this.errorService.createBadRequestError("No check ID in request");
}
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const updatedCheck = await this.db.checkModule.ackCheck(checkId, teamId, ack);
return updatedCheck;
};
ackAllChecks = async ({ monitorId, path, teamId, ack }) => {
if (path === "monitor") {
if (!monitorId) {
throw this.errorService.createBadRequestError("No monitor ID in request");
}
const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor) {
throw this.errorService.createNotFoundError("Monitor not found");
}
if (!monitor.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
}
const updatedChecks = await this.db.checkModule.ackAllChecks(monitorId, teamId, ack, path);
return updatedChecks;
};
deleteChecks = async ({ monitorId, teamId }) => {
if (!monitorId) {
throw this.errorService.createBadRequestError("No monitor ID in request");
}
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor) {
throw this.errorService.createNotFoundError("Monitor not found");
}
if (!monitor.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
const deletedCount = await this.db.checkModule.deleteChecks(monitorId);
return deletedCount;
};
deleteChecksByTeamId = async ({ teamId }) => {
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const deletedCount = await this.db.checkModule.deleteChecksByTeamId(teamId);
return deletedCount;
};
updateChecksTTL = async ({ teamId, ttl }) => {
const SECONDS_PER_DAY = 86400;
const newTTL = parseInt(ttl, 10) * SECONDS_PER_DAY;
await this.db.checkModule.updateChecksTTL(teamId, newTTL);
};
}
export default CheckService;
@@ -0,0 +1,94 @@
import v8 from "v8";
import os from "os";
const SERVICE_NAME = "diagnosticService";
class DiagnosticService {
static SERVICE_NAME = SERVICE_NAME;
constructor() {
/**
* Performance Observer for monitoring system performance metrics.
* Clears performance marks after each measurement to prevent memory leaks.
*/
const obs = new PerformanceObserver((items) => {
// Get the first entry but we don't need to store it
items.getEntries()[0];
performance.clearMarks();
});
obs.observe({ entryTypes: ["measure"] });
}
get serviceName() {
return DiagnosticService.SERVICE_NAME;
}
getCPUUsage = async () => {
const startUsage = process.cpuUsage();
const timingPeriod = 1000; // measured in ms
await new Promise((resolve) => setTimeout(resolve, timingPeriod));
const endUsage = process.cpuUsage(startUsage);
const cpuUsage = {
userUsageMs: endUsage.user / 1000,
systemUsageMs: endUsage.system / 1000,
usagePercentage: ((endUsage.user + endUsage.system) / 1000 / timingPeriod) * 100,
};
return cpuUsage;
};
getSystemStats = async () => {
// Memory Usage
const totalMemory = os.totalmem();
const freeMemory = os.freemem();
const osStats = {
freeMemoryBytes: freeMemory, // bytes
totalMemoryBytes: totalMemory, // bytes
};
const used = process.memoryUsage();
const memoryUsage = {};
for (let key in used) {
memoryUsage[`${key}Mb`] = Math.round((used[key] / 1024 / 1024) * 100) / 100; // MB
}
// CPU Usage
const cpuMetrics = await this.getCPUUsage();
// V8 Heap Statistics
const heapStats = v8.getHeapStatistics();
const v8Metrics = {
totalHeapSizeBytes: heapStats.total_heap_size, // bytes
usedHeapSizeBytes: heapStats.used_heap_size, // bytes
heapSizeLimitBytes: heapStats.heap_size_limit, // bytes
};
// Event Loop Delay
let eventLoopDelay = 0;
performance.mark("start");
await new Promise((resolve) => setTimeout(resolve, 0));
performance.mark("end");
performance.measure("eventLoopDelay", "start", "end");
const entries = performance.getEntriesByName("eventLoopDelay");
if (entries.length > 0) {
eventLoopDelay = entries[0].duration;
}
// Uptime
const uptimeMs = process.uptime() * 1000; // ms
// Combine Metrics
const diagnostics = {
osStats,
memoryUsage,
cpuUsage: cpuMetrics,
v8HeapStats: v8Metrics,
eventLoopDelayMs: eventLoopDelay,
uptimeMs,
};
return diagnostics;
};
}
export default DiagnosticService;
@@ -0,0 +1,414 @@
const SERVICE_NAME = "incidentService";
class IncidentService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, logger, errorService, stringService }) {
this.db = db;
this.logger = logger;
this.errorService = errorService;
this.stringService = stringService;
}
get serviceName() {
return IncidentService.SERVICE_NAME;
}
createIncident = async (monitor, check) => {
try {
if (!monitor || !monitor._id) {
throw this.errorService.createBadRequestError("Monitor is required");
}
if (!check || !check._id) {
throw this.errorService.createBadRequestError("Check is required");
}
const activeIncident = await this.db.incidentModule.getActiveIncidentByMonitor(monitor._id);
if (activeIncident) {
await this.db.incidentModule.addCheckToIncident(activeIncident._id, check._id);
this.logger.info({
service: this.SERVICE_NAME,
method: "createIncident",
message: `Check added to existing active incident for monitor ${monitor.name}`,
incidentId: activeIncident._id,
monitorId: monitor._id,
});
return activeIncident;
}
const incidentData = {
monitorId: monitor._id,
teamId: monitor.teamId,
type: monitor.type,
startTime: new Date(),
status: true,
message: check.message || null,
statusCode: check.statusCode || null,
checks: [check._id],
};
const incident = await this.db.incidentModule.createIncident(incidentData);
this.logger.info({
service: this.SERVICE_NAME,
method: "createIncident",
message: `New incident created for monitor ${monitor.name}`,
incidentId: incident._id,
monitorId: monitor._id,
});
return incident;
} catch (error) {
this.logger.error({
service: this.SERVICE_NAME,
method: "createIncident",
message: error.message,
monitorId: monitor?._id,
error: error.stack,
});
throw error;
}
};
resolveIncident = async (monitor, check) => {
try {
if (!monitor || !monitor._id) {
throw this.errorService.createBadRequestError("Monitor is required");
}
const activeIncident = await this.db.incidentModule.getActiveIncidentByMonitor(monitor._id);
if (!activeIncident) {
this.logger.info({
service: this.SERVICE_NAME,
method: "resolveIncident",
message: `No active incident found for monitor ${monitor.name}`,
monitorId: monitor._id,
});
return null;
}
await this.db.incidentModule.addCheckToIncident(activeIncident._id, check._id);
const resolvedIncident = await this.db.incidentModule.resolveIncident(activeIncident._id, {
resolutionType: "automatic",
resolvedBy: null,
endTime: new Date(),
});
this.logger.info({
service: this.SERVICE_NAME,
method: "resolveIncident",
message: `Incident automatically resolved for monitor ${monitor.name}`,
incidentId: resolvedIncident._id,
monitorId: monitor._id,
});
return resolvedIncident;
} catch (error) {
this.logger.error({
service: this.SERVICE_NAME,
method: "resolveIncident",
message: error.message,
monitorId: monitor?._id,
error: error.stack,
});
throw error;
}
};
resolveIncidentManually = async ({ incidentId, userId, teamId, comment }) => {
try {
if (!incidentId) {
throw this.errorService.createBadRequestError("No incident ID in request");
}
if (!userId) {
throw this.errorService.createBadRequestError("No user ID in request");
}
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const incident = await this.db.incidentModule.getIncidentById(incidentId);
if (!incident) {
throw this.errorService.createNotFoundError("Incident not found");
}
if (!incident.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
if (incident.status === false) {
throw this.errorService.createBadRequestError("Incident is already resolved");
}
const resolvedIncident = await this.db.incidentModule.resolveIncident(incidentId, {
resolutionType: "manual",
resolvedBy: userId,
comment: comment || null,
endTime: new Date(),
});
this.logger.info({
service: this.SERVICE_NAME,
method: "resolveIncidentManually",
message: `Incident manually resolved by user`,
incidentId: resolvedIncident._id,
userId,
});
return resolvedIncident;
} catch (error) {
this.logger.error({
service: this.SERVICE_NAME,
method: "resolveIncidentManually",
message: error.message,
incidentId,
error: error.stack,
});
throw error;
}
};
getIncidentsByTeam = async ({ teamId, query }) => {
try {
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const { sortOrder, dateRange, page, rowsPerPage, status, monitorId, resolutionType } = query || {};
const result = await this.db.incidentModule.getIncidentsByTeam({
teamId,
sortOrder,
dateRange,
page,
rowsPerPage,
status,
monitorId,
resolutionType,
});
return result;
} catch (error) {
this.logger.error({
service: this.SERVICE_NAME,
method: "getIncidentsByTeam",
message: error.message,
teamId,
error: error.stack,
});
throw error;
}
};
getIncidentSummary = async ({ teamId, query }) => {
try {
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const { limit } = query || {};
const summary = await this.db.incidentModule.getIncidentSummary({
teamId,
limit,
});
return summary;
} catch (error) {
this.logger.error({
service: this.SERVICE_NAME,
method: "getIncidentSummary",
message: error.message,
teamId,
error: error.stack,
});
throw error;
}
};
getIncidentById = async ({ incidentId, teamId }) => {
try {
if (!incidentId) {
throw this.errorService.createBadRequestError("No incident ID in request");
}
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
const incident = await this.db.incidentModule.getIncidentById(incidentId);
if (!incident) {
throw this.errorService.createNotFoundError("Incident not found");
}
if (!incident.teamId.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
return incident;
} catch (error) {
this.logger.error({
service: this.SERVICE_NAME,
method: "getIncidentById",
message: error.message,
incidentId,
error: error.stack,
});
throw error;
}
};
processIncidentsFromBuffer = async (incidentBufferItems) => {
try {
if (!incidentBufferItems || incidentBufferItems.length === 0) {
return;
}
const createItems = [];
const resolveItems = [];
for (const item of incidentBufferItems) {
if (item.action === "resolve") {
resolveItems.push(item);
} else {
createItems.push(item);
}
}
for (const item of resolveItems) {
try {
await this.resolveIncident(item.monitor, item.check);
} catch (error) {
this.logger.error({
service: this.SERVICE_NAME,
method: "processIncidentsFromBuffer",
message: `Failed to resolve incident from buffer: ${error.message}`,
monitorId: item.monitor?._id,
error: error.stack,
});
}
}
if (createItems.length === 0) {
return;
}
const groupedByMonitor = {};
for (const item of createItems) {
if (!item.monitor || !item.monitor._id || !item.check || !item.check._id) {
this.logger.warn({
service: this.SERVICE_NAME,
method: "processIncidentsFromBuffer",
message: "Skipping item with missing monitor or check data",
item,
});
continue;
}
const monitorId = item.monitor._id.toString();
if (!groupedByMonitor[monitorId]) {
groupedByMonitor[monitorId] = [];
}
groupedByMonitor[monitorId].push(item);
}
const monitorIds = Object.keys(groupedByMonitor);
if (monitorIds.length === 0) {
return;
}
const activeIncidents = await this.db.incidentModule.getActiveIncidentsByMonitors(monitorIds);
const incidentsCreatedInFlush = {};
const checksToAddToIncidents = [];
const newIncidentsToCreate = [];
for (const [monitorId, items] of Object.entries(groupedByMonitor)) {
const existingIncident = activeIncidents.get(monitorId) || incidentsCreatedInFlush[monitorId];
if (existingIncident) {
const incidentId = existingIncident._id ? existingIncident._id.toString() : existingIncident;
for (const item of items) {
checksToAddToIncidents.push({
incidentId,
checkId: item.check._id.toString(),
});
}
} else {
const firstItem = items[0];
const incidentData = {
monitorId: firstItem.monitor._id,
teamId: firstItem.monitor.teamId,
type: firstItem.monitor.type,
startTime: new Date(),
status: true,
message: firstItem.check.message || null,
statusCode: firstItem.check.statusCode || null,
checks: [firstItem.check._id],
};
newIncidentsToCreate.push({
incidentData,
monitorId,
remainingChecks: items.slice(1), // Checks restantes para agregar después
});
}
}
if (newIncidentsToCreate.length > 0) {
const incidentDataArray = newIncidentsToCreate.map((item) => item.incidentData);
await this.db.incidentModule.createIncidents(incidentDataArray);
const createdIncidentsMap = await this.db.incidentModule.getActiveIncidentsByMonitors(newIncidentsToCreate.map((item) => item.monitorId));
for (const item of newIncidentsToCreate) {
const createdIncident = createdIncidentsMap.get(item.monitorId);
if (createdIncident && createdIncident._id) {
const incidentId = createdIncident._id.toString();
incidentsCreatedInFlush[item.monitorId] = incidentId;
for (const remainingItem of item.remainingChecks) {
checksToAddToIncidents.push({
incidentId,
checkId: remainingItem.check._id.toString(),
});
}
}
}
}
if (checksToAddToIncidents.length > 0) {
await this.db.incidentModule.addChecksToIncidentsBatch(checksToAddToIncidents);
}
this.logger.info({
service: this.SERVICE_NAME,
method: "processIncidentsFromBuffer",
message: `Processed ${incidentBufferItems.length} incident buffer items`,
created: newIncidentsToCreate.length,
checksAdded: checksToAddToIncidents.length,
resolved: resolveItems.length,
});
} catch (error) {
this.logger.error({
service: this.SERVICE_NAME,
method: "processIncidentsFromBuffer",
message: error.message,
error: error.stack,
});
throw error;
}
};
}
export default IncidentService;
@@ -0,0 +1,44 @@
const SERVICE_NAME = "inviteService";
class InviteService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, settingsService, emailService, stringService, errorService }) {
this.db = db;
this.settingsService = settingsService;
this.emailService = emailService;
this.stringService = stringService;
this.errorService = errorService;
}
get serviceName() {
return InviteService.SERVICE_NAME;
}
getInviteToken = async ({ invite, teamId }) => {
invite.teamId = teamId;
const inviteToken = await this.db.inviteModule.requestInviteToken(invite);
return inviteToken;
};
sendInviteEmail = async ({ inviteRequest, firstName }) => {
const inviteToken = await this.db.inviteModule.requestInviteToken({ ...inviteRequest });
const { clientHost } = this.settingsService.getSettings();
const html = await this.emailService.buildEmail("employeeActivationTemplate", {
name: firstName,
link: `${clientHost}/register/${inviteToken.token}`,
});
const result = await this.emailService.sendEmail(inviteRequest.email, "Welcome to Uptime Monitor", html);
if (!result) {
throw this.errorService.createServerError("Failed to send invite e-mail... Please verify your settings.");
}
};
verifyInviteToken = async ({ inviteToken }) => {
const invite = await this.db.inviteModule.getInviteToken(inviteToken);
return invite;
};
}
export default InviteService;
@@ -0,0 +1,66 @@
const SERVICE_NAME = "maintenanceWindowService";
class MaintenanceWindowService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, settingsService, stringService, errorService }) {
this.db = db;
this.settingsService = settingsService;
this.stringService = stringService;
this.errorService = errorService;
}
get serviceName() {
return MaintenanceWindowService.SERVICE_NAME;
}
createMaintenanceWindow = async ({ teamId, body }) => {
const monitorIds = body.monitors;
const monitors = await this.db.monitorModule.getMonitorsByIds(monitorIds);
const unauthorizedMonitors = monitors.filter((monitor) => !monitor.teamId.equals(teamId));
if (unauthorizedMonitors.length > 0) {
throw this.errorService.createAuthorizationError();
}
const dbTransactions = monitorIds.map((monitorId) => {
return this.db.maintenanceWindowModule.createMaintenanceWindow({
teamId,
monitorId,
name: body.name,
active: body.active ? body.active : true,
repeat: body.repeat,
start: body.start,
end: body.end,
});
});
await Promise.all(dbTransactions);
};
getMaintenanceWindowById = async ({ id, teamId }) => {
const maintenanceWindow = await this.db.maintenanceWindowModule.getMaintenanceWindowById({ id, teamId });
return maintenanceWindow;
};
getMaintenanceWindowsByTeamId = async ({ teamId, query }) => {
const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByTeamId(teamId, query);
return maintenanceWindows;
};
getMaintenanceWindowsByMonitorId = async ({ monitorId, teamId }) => {
const maintenanceWindows = await this.db.maintenanceWindowModule.getMaintenanceWindowsByMonitorId({ monitorId, teamId });
return maintenanceWindows;
};
deleteMaintenanceWindow = async ({ id, teamId }) => {
await this.db.maintenanceWindowModule.deleteMaintenanceWindowById({ id, teamId });
};
editMaintenanceWindow = async ({ id, teamId, body }) => {
const editedMaintenanceWindow = await this.db.maintenanceWindowModule.editMaintenanceWindowById({ id, body, teamId });
return editedMaintenanceWindow;
};
}
export default MaintenanceWindowService;
@@ -0,0 +1,317 @@
import { createMonitorsBodyValidation } from "@/validation/joi.js";
const SERVICE_NAME = "MonitorService";
class MonitorService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ db, settingsService, jobQueue, stringService, emailService, papaparse, logger, errorService, games }) {
this.db = db;
this.settingsService = settingsService;
this.jobQueue = jobQueue;
this.stringService = stringService;
this.emailService = emailService;
this.papaparse = papaparse;
this.logger = logger;
this.errorService = errorService;
this.games = games;
}
get serviceName() {
return MonitorService.SERVICE_NAME;
}
verifyTeamAccess = async ({ teamId, monitorId }) => {
const monitor = await this.db.monitorModule.getMonitorById(monitorId);
if (!monitor?.teamId?.equals(teamId)) {
throw this.errorService.createAuthorizationError();
}
};
getAllMonitors = async () => {
const monitors = await this.db.monitorModule.getAllMonitors();
return monitors;
};
getUptimeDetailsById = async ({ teamId, monitorId, dateRange, normalize }) => {
await this.verifyTeamAccess({ teamId, monitorId });
const data = await this.db.monitorModule.getUptimeDetailsById({
monitorId,
dateRange,
normalize,
});
return data;
};
getMonitorStatsById = async ({ teamId, monitorId, limit, sortOrder, dateRange, numToDisplay, normalize }) => {
await this.verifyTeamAccess({ teamId, monitorId });
const monitorStats = await this.db.monitorModule.getMonitorStatsById({
monitorId,
limit,
sortOrder,
dateRange,
numToDisplay,
normalize,
});
return monitorStats;
};
getHardwareDetailsById = async ({ teamId, monitorId, dateRange }) => {
await this.verifyTeamAccess({ teamId, monitorId });
const monitor = await this.db.monitorModule.getHardwareDetailsById({ monitorId, dateRange });
return monitor;
};
getMonitorById = async ({ teamId, monitorId }) => {
await this.verifyTeamAccess({ teamId, monitorId });
const monitor = await this.db.monitorModule.getMonitorById(monitorId);
return monitor;
};
createMonitor = async ({ teamId, userId, body }) => {
const monitor = await this.db.monitorModule.createMonitor({
body,
teamId,
userId,
});
this.jobQueue.addJob(monitor._id, monitor);
};
createBulkMonitors = async ({ fileData, userId, teamId }) => {
const { parse } = this.papaparse;
return new Promise((resolve, reject) => {
parse(fileData, {
header: true,
skipEmptyLines: true,
transform: (value, header) => {
if (value === "") return undefined; // Empty fields become undefined
// Handle 'port' and 'interval' fields, check if they're valid numbers
if (["port", "interval"].includes(header)) {
const num = parseInt(value, 10);
if (isNaN(num)) {
throw this.errorService.createBadRequestError(`${header} should be a valid number, got: ${value}`);
}
return num;
}
return value;
},
complete: async ({ data, errors }) => {
try {
if (errors.length > 0) {
throw this.errorService.createServerError("Error parsing CSV");
}
if (!data || data.length === 0) {
throw this.errorService.createServerError("CSV file contains no data rows");
}
const enrichedData = data.map((monitor) => ({
userId,
teamId,
...monitor,
description: monitor.description || monitor.name || monitor.url,
name: monitor.name || monitor.url,
type: monitor.type || "http",
}));
await createMonitorsBodyValidation.validateAsync(enrichedData);
const monitors = await this.db.monitorModule.createBulkMonitors(enrichedData);
await Promise.all(
monitors.map(async (monitor) => {
this.jobQueue.addJob(monitor._id, monitor);
})
);
resolve(monitors);
} catch (error) {
reject(error);
}
},
});
});
};
deleteMonitor = async ({ teamId, monitorId }) => {
await this.verifyTeamAccess({ teamId, monitorId });
const monitor = await this.db.monitorModule.deleteMonitor({ teamId, monitorId });
await this.jobQueue.deleteJob(monitor);
await this.db.statusPageModule.deleteStatusPagesByMonitorId(monitor._id);
return monitor;
};
deleteAllMonitors = async ({ teamId }) => {
const { monitors, deletedCount } = await this.db.monitorModule.deleteAllMonitors(teamId);
await Promise.all(
monitors.map(async (monitor) => {
try {
await this.jobQueue.deleteJob(monitor);
await this.db.checkModule.deleteChecks(monitor._id);
await this.db.pageSpeedCheckModule.deletePageSpeedChecksByMonitorId(monitor._id);
await this.db.notificationsModule.deleteNotificationsByMonitorId(monitor._id);
} catch (error) {
this.logger.warn({
message: `Error deleting associated records for monitor ${monitor._id} with name ${monitor.name}`,
service: SERVICE_NAME,
method: "deleteAllMonitors",
stack: error.stack,
});
}
})
);
return deletedCount;
};
editMonitor = async ({ teamId, monitorId, body }) => {
await this.verifyTeamAccess({ teamId, monitorId });
const editedMonitor = await this.db.monitorModule.editMonitor({ monitorId, body });
await this.jobQueue.updateJob(editedMonitor);
};
pauseMonitor = async ({ teamId, monitorId }) => {
await this.verifyTeamAccess({ teamId, monitorId });
const monitor = await this.db.monitorModule.pauseMonitor({ monitorId });
monitor.isActive === true ? await this.jobQueue.resumeJob(monitor._id, monitor) : await this.jobQueue.pauseJob(monitor);
return monitor;
};
addDemoMonitors = async ({ userId, teamId }) => {
const demoMonitors = await this.db.monitorModule.addDemoMonitors(userId, teamId);
await Promise.all(demoMonitors.map((monitor) => this.jobQueue.addJob(monitor._id, monitor)));
return demoMonitors;
};
sendTestEmail = async ({ to }) => {
const subject = this.stringService.testEmailSubject;
const context = { testName: "Monitoring System" };
const html = await this.emailService.buildEmail("testEmailTemplate", context);
const messageId = await this.emailService.sendEmail(to, subject, html);
if (!messageId) {
throw this.errorService.createServerError("Failed to send test email.");
}
return messageId;
};
getMonitorsByTeamId = async ({ teamId, limit, type, page, rowsPerPage, filter, field, order }) => {
const monitors = await this.db.monitorModule.getMonitorsByTeamId({
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
teamId,
});
return monitors;
};
getMonitorsAndSummaryByTeamId = async ({ teamId, type, explain }) => {
const result = await this.db.monitorModule.getMonitorsAndSummaryByTeamId({
type,
explain,
teamId,
});
return result;
};
getMonitorsWithChecksByTeamId = async ({ teamId, limit, type, page, rowsPerPage, filter, field, order, explain }) => {
const result = await this.db.monitorModule.getMonitorsWithChecksByTeamId({
limit,
type,
page,
rowsPerPage,
filter,
field,
order,
teamId,
explain,
});
return result;
};
exportMonitorsToCSV = async ({ teamId }) => {
const monitors = await this.db.monitorModule.getMonitorsByTeamId({ teamId });
if (!monitors || monitors.length === 0) {
throw this.errorService.createNotFoundError("No monitors to export");
}
const csvData = monitors?.filteredMonitors?.map((monitor) => ({
name: monitor.name,
description: monitor.description,
type: monitor.type,
url: monitor.url,
interval: monitor.interval,
port: monitor.port,
ignoreTlsErrors: monitor.ignoreTlsErrors,
isActive: monitor.isActive,
}));
const csv = this.papaparse.unparse(csvData);
return csv;
};
exportMonitorsToJSON = async ({ teamId }) => {
const monitors = await this.db.monitorModule.getMonitorsByTeamId({ teamId });
if (!monitors || monitors.length === 0) {
throw this.errorService.createNotFoundError("No monitors to export");
}
const json = monitors?.filteredMonitors
?.map((monitor) => {
const initialType = monitor.type;
let parsedType;
if (initialType === "hardware") {
parsedType = "infrastructure";
} else if (initialType === "http") {
if (monitor.url.startsWith("https://")) {
parsedType = "https";
} else {
parsedType = "http";
}
} else if (initialType === "pagespeed") {
parsedType = initialType;
} else {
// Skip unsupported types
return;
}
return {
name: monitor.name,
url: monitor.url,
type: parsedType,
interval: monitor.interval,
n: monitor.statusWindowSize,
secret: monitor.secret,
};
})
.filter(Boolean);
return json;
};
getAllGames = () => {
return this.games;
};
getGroupsByTeamId = async ({ teamId }) => {
const groups = await this.db.monitorModule.getGroupsByTeamId({ teamId });
return groups;
};
}
export default MonitorService;
+219
View File
@@ -0,0 +1,219 @@
const SERVICE_NAME = "userService";
class UserService {
static SERVICE_NAME = SERVICE_NAME;
constructor({ crypto, db, emailService, settingsService, logger, stringService, jwt, errorService, jobQueue }) {
this.db = db;
this.emailService = emailService;
this.settingsService = settingsService;
this.logger = logger;
this.stringService = stringService;
this.jwt = jwt;
this.errorService = errorService;
this.jobQueue = jobQueue;
this.crypto = crypto;
}
get serviceName() {
return UserService.SERVICE_NAME;
}
issueToken = (payload, appSettings) => {
const tokenTTL = appSettings?.jwtTTL ?? "2h";
const tokenSecret = appSettings?.jwtSecret;
const payloadData = payload;
return this.jwt.sign(payloadData, tokenSecret, { expiresIn: tokenTTL });
};
registerUser = async (user, file) => {
// Create a new user
// If superAdmin exists, a token should be attached to all further register requests
const superAdminExists = await this.db.userModule.checkSuperadmin();
if (superAdminExists) {
const invitedUser = await this.db.inviteModule.getInviteTokenAndDelete(user.inviteToken);
user.role = invitedUser.role;
user.teamId = invitedUser.teamId;
} else {
// This is the first account, create JWT secret to use if one is not supplied by env
const jwtSecret = this.crypto.randomBytes(64).toString("hex");
await this.db.settingsModule.updateAppSettings({ jwtSecret });
}
const newUser = await this.db.userModule.insertUser({ ...user }, file);
this.logger.debug({
message: "New user created",
service: SERVICE_NAME,
method: "registerUser",
details: newUser._id,
});
const userForToken = { ...newUser._doc };
delete userForToken.profileImage;
delete userForToken.avatarImage;
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userForToken, appSettings);
try {
const html = await this.emailService.buildEmail("welcomeEmailTemplate", {
name: newUser.firstName,
});
this.emailService.sendEmail(newUser.email, "Welcome to Uptime Monitor", html).catch((error) => {
this.logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
});
} catch (error) {
this.logger.warn({
message: error.message,
service: SERVICE_NAME,
method: "registerUser",
stack: error.stack,
});
}
return { user: newUser, token };
};
loginUser = async (email, password) => {
// Check if user exists
const user = await this.db.userModule.getUserByEmail(email);
// Compare password
const match = await user.comparePassword(password);
if (match !== true) {
throw this.errorService.createAuthenticationError(this.stringService.authIncorrectPassword);
}
// Remove password from user object. Should this be abstracted to DB layer?
const userWithoutPassword = { ...user._doc };
delete userWithoutPassword.password;
delete userWithoutPassword.avatarImage;
// Happy path, return token
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(userWithoutPassword, appSettings);
// reset avatar image
userWithoutPassword.avatarImage = user.avatarImage;
return { user: userWithoutPassword, token };
};
editUser = async (updates, file, currentUser) => {
// Change Password check
if (updates?.password && updates?.newPassword) {
// Get user's email
// Add user email to body for DB operation
updates.email = currentUser.email;
// Get user
const user = await this.db.userModule.getUserByEmail(currentUser.email);
// Compare passwords
const match = await user.comparePassword(updates?.password);
// If not a match, throw a 403
// 403 instead of 401 to avoid triggering axios interceptor
if (!match) {
throw this.errorService.createAuthorizationError(this.stringService.authIncorrectPassword);
}
// If a match, update the password
updates.password = updates.newPassword;
}
const updatedUser = await this.db.userModule.updateUser({ userId: currentUser?._id, user: updates, file: file });
return updatedUser;
};
checkSuperadminExists = async () => {
const superAdminExists = await this.db.userModule.checkSuperadmin();
return superAdminExists;
};
requestRecovery = async (email) => {
const user = await this.db.userModule.getUserByEmail(email);
const recoveryToken = await this.db.recoveryModule.requestRecoveryToken(email);
const name = user.firstName;
const { clientHost } = this.settingsService.getSettings();
const url = `${clientHost}/set-new-password/${recoveryToken.token}`;
const html = await this.emailService.buildEmail("passwordResetTemplate", {
name,
email,
url,
});
const msgId = await this.emailService.sendEmail(email, "Checkmate Password Reset", html);
return msgId;
};
validateRecovery = async (recoveryToken) => {
await this.db.recoveryModule.validateRecoveryToken(recoveryToken);
};
resetPassword = async (password, recoveryToken) => {
const user = await this.db.recoveryModule.resetPassword(password, recoveryToken);
const appSettings = await this.settingsService.getSettings();
const token = this.issueToken(user._doc, appSettings);
return { user, token };
};
deleteUser = async (user) => {
const email = user?.email;
if (!email) {
throw this.errorService.createBadRequestError("No email in request");
}
const teamId = user?.teamId;
const userId = user?._id;
if (!teamId) {
throw this.errorService.createBadRequestError("No team ID in request");
}
if (!userId) {
throw this.errorService.createBadRequestError("No user ID in request");
}
const roles = user?.role;
if (roles.includes("demo")) {
throw this.errorService.createBadRequestError("Demo user cannot be deleted");
}
// 1. Find all the monitors associated with the team ID if superadmin
const result = await this.db.monitorModule.getMonitorsByTeamId({
teamId: teamId,
});
if (roles.includes("superadmin")) {
// 2. Remove all jobs, delete checks and alerts
result?.monitors.length > 0 &&
(await Promise.all(
result.monitors.map(async (monitor) => {
await this.jobQueue.deleteJob(monitor);
})
));
}
// 6. Delete the user by id
await this.db.userModule.deleteUser(userId);
};
getAllUsers = async () => {
const users = await this.db.userModule.getAllUsers();
return users;
};
getUserById = async (roles, userId) => {
const user = await this.db.userModule.getUserById(roles, userId);
return user;
};
editUserById = async (userId, user) => {
await this.db.userModule.editUserById(userId, user);
};
setPasswordByUserId = async (userId, password) => {
const updatedUser = await this.db.userModule.updateUser({ userId: userId, user: { password: password }, file: null });
return updatedUser;
};
}
export default UserService;